Tuesday, December 31, 2013

Install PySide for Python 3 on Raspberry Pi

Enter the command to install PySide for Python 3:

$ sudo apt-get install python3-pyside

In Python 3, or IDLE3, enter:

import PySide

If no error reported, means PySide installed successfully. To check the installed version of PySide, enter:

PySide.__version__

Enter "Hello World" of Python 3 with PySide.
#!/usr/bin/python3

import sys
from PySide.QtCore import *
from PySide.QtGui import *

app = QApplication(sys.argv)
label=QLabel("Hello World")
label.show()
app.exec_()
sys.exit()

PySide for Python 3
PySide for Python 3




Related: Install PySide for Python 2 on Raspberry Pi

Install PySide for Python 2 on Raspberry Pi

PySide is an open source software project providing Python bindings for the Qt framework. To install PySide for Python 2 on Raspberry Pi, enter the command:
$ sudo apt-get install python-pyside

In Python, or IDLE, enter:

import PySide

If no error reported, means PySide installed successfully.
To check the installed version of PySide, enter:

PySide.__version__

Currently, version 1.1.1 installed.


"Hello World" of PySide for Python

Create a py module with the code, and run it.
#!/usr/bin/python

import sys
from PySide.QtCore import *
from PySide.QtGui import *

app = QApplication(sys.argv)
label=QLabel("Hello World")
label.show()
app.exec_()
sys.exit()

"Hello World" of PySide for Python
"Hello World" of PySide for Python





Related: Install PySide for Python 3 on Raspberry Pi

Java exercise: Schedule tasks run in a background thread using java.util.Timer

This example run a background task repeatly in 5 seconds to print system time.
java.util.Timer
Example of using java.util.Timer
import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;
import java.util.Date;

/**
 * @web helloraspberrypi.blogspot.com
 */
class testTimer{

    public static void main(String[] args) {
        Timer timer = new Timer(); 
        TimerTask timeTask = new TimerTask() {
            
            @Override
            public void run() {
                System.out.println((new Date()).toString());
            }
        };
        timer.schedule(timeTask, 0, 5000);
        
        System.out.println("Press ENTER to exit");
        
        try{
            System.in.read();
        }catch(IOException ex){
            System.out.println(ex.toString());
        }
        
        System.out.println("-BYE-");
        timer.cancel();
    }
}


Monday, December 30, 2013

How Raspberry Pi browsers support HTML5

This post compare how well the browsers in Raspberry Pi support HTML5, by visiting http://html5test.com. Tested browsers include the Pi's default browser Midori, Chromium by Google, and Iceweasel by Mozilla.

Midori 0.4.3
Midori 0.4.3

Chromium 22.0.1229.94 Built on Debian 7.0
Chromium 22.0.1229.94 Built on Debian 7.0

Iceweasel 17.0.9
Iceweasel 17.0.9

Install Iceweasel browser on Raspberry Pi

Iceweasel is a derivative of Mozilla Firefox browser. To install Iceweasel, enter the command:
$ sudo apt-get install iceweasel

To run Iceweasel, enter the command:
$ iceweasel

or click Start > Internet > Iceweasel
Iceweasel browser on Raspberry Pi
Iceweasel browser on Raspberry Pi





Related:
- Install Chromium on Raspberry Pi
How Raspberry Pi browsers support HTML5

Change text size of LXTerminal

To change text size of LXTerminal:

- Select Edit -> Preferences

- Click the Terminal Font button

- Select Size, and click OK.



Python in Practice: Create Better Programs Using Concurrency, Libraries, and Patterns (Developer's Library)

Python in Practice
Python in Practice
“Whether you are an experienced programmer or are starting your career, Python in Practice is full of valuable advice and example to help you improve your craft by thinking about problems from different perspectives, introducing tools, and detailing techniques to create more effective solutions.”
Doug Hellmann, Senior Developer, DreamHost

If you’re an experienced Python programmer, Python in Practice will help you improve the quality, reliability, speed, maintainability, and usability of all your Python programs.

Mark Summerfield focuses on four key themes: design patterns for coding elegance, faster processing through concurrency and compiled Python (Cython), high-level networking, and graphics. He identifies well-proven design patterns that are useful in Python, illuminates them with expert-quality code, and explains why some object-oriented design patterns are irrelevant to Python. He also explodes several counterproductive myths about Python programming–showing, for example, how Python can take full advantage of multicore hardware.

All examples, including three complete case studies, have been tested with Python 3.3 (and, where possible, Python 3.2 and 3.1) and crafted to maintain compatibility with future Python 3.x versions. All code has been tested on Linux, and most code has also been tested on OS X and Windows. All code may be downloaded at www.qtrac.eu/pipbook.html.

Coverage includes
  • Leveraging Python’s most effective creational, structural, and behavioral design patterns
  • Supporting concurrency with Python’s multiprocessing, threading, and concurrent.futures modules
  • Avoiding concurrency problems using thread-safe queues and futures rather than fragile locks
  • Simplifying networking with high-level modules, including xmlrpclib and RPyC
  • Accelerating Python code with Cython, C-based Python modules, profiling, and other techniques
  • Creating modern-looking GUI applications with Tkinter
  • Leveraging today’s powerful graphics hardware via the OpenGL API using pyglet and PyOpenGL

Sunday, December 29, 2013

Java exercise - Client and Server example V, pass ArrayList of object in socket

This Java Client/Server example demonstrate how to pass ArrayList of String in socket.

Pass ArrayList of String in socket
Pass ArrayList of String in socket

Java code in host side:
import java.io.IOException;
import java.io.OutputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class hostList {
    
    static ArrayList<String> myList;

    public static void main(String srgs[]) {

        int count = 0;
        
        initList();

        //hard code to use port 8080
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            
            System.out.println("I'm waiting here: " + serverSocket.getLocalPort());
            
            while (true) {
                
                try {
                    Socket socket = serverSocket.accept();
                            
                    count++;
                    System.out.println("#" + count + " from "
                            + socket.getInetAddress() + ":" 
                            + socket.getPort());
                    
                    HostThread myHostThread = new HostThread(socket, count);
                    myHostThread.start();
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
    
    private static class HostThread extends Thread{
        
        private Socket hostThreadSocket;
        int cnt;
        
        HostThread(Socket socket, int c){
            hostThreadSocket = socket;
            cnt = c;
        }

        @Override
        public void run() {
            
            OutputStream outputStream;
            try {
                outputStream = hostThreadSocket.getOutputStream();
                try (ObjectOutputStream objectOutputStream = 
                    new ObjectOutputStream(outputStream)) {
                        objectOutputStream.writeObject(myList);
                }
            } catch (IOException ex) {
                System.out.println(ex.toString());
            }finally{
                try {
                    hostThreadSocket.close();
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }

        }
    }
    
    private static void initList(){
        // init myList with dummy data
        myList =  new ArrayList<String>();
        myList.add("Hello");
        myList.add("Raspberry Pi");
        myList.add("from");
        myList.add("helloraspberrypi.blogspot.com");
    }
}

Java code in client side:
import java.net.Socket;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.ObjectInputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;

class clientList{

    public static void main(String args[])
    { 
        if(args.length == 0){
            System.out.println("usage: java client <port>");
            System.exit(1);
        }
        
        int port = isParseInt(args[0]);
        if(port == -1){
            System.out.println("usage: java client <port>");
            System.out.println("<port>: integer");
            System.exit(1);
        }
        
        try{
            //IP is hard coded
            //port is user entry
            Socket socket = new Socket("192.168.111.109", port);
            
            ArrayList<String> myList;
            
            ObjectInputStream objectInputStream = 
                new ObjectInputStream(socket.getInputStream());
            try{
                Object object = objectInputStream.readObject();
                myList = (ArrayList<String>)object;
                    
                for (String s : myList) {
                    System.out.println(s);
                }
                    
            }catch(ClassNotFoundException ex){
                System.out.println(ex.toString());
            }

            socket.close();            
        }catch(UnknownHostException e){
            System.out.println(e.toString());
        }catch(IOException e){
            System.out.println(e.toString());
        }

    }

    private static int isParseInt(String str){
        
        int num = -1;
        try{
             num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
        }
        
        return num;
    }
    
}




Download source code.



Java exercise - Implement client and server to communicate using Socket, step-by-step.

Wednesday, December 25, 2013

Java exercise - Client and Server example IV, with option to request Read Temperature

Continue on last exercise of Java Client-Server exercise, with the function of reading system temperature in Raspberry Pi. The host.java and client.java are modified to handle option parameter passed in Client-Server Socket communication, such that host can response with temperature if requested.

Java Client-Server Socket communication, with option of reading Raspberry Pi's system temperature.
Java Client-Server Socket communication, with option of reading Raspberry Pi's system temperature.
Request to read temperature (RQS_TEMP) is hard coded in client side, client.java
import java.net.Socket;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.UnknownHostException;

class client{
    
    final static Integer RQS_DEFAULT = 0;
    final static Integer RQS_TEMP = 1;

    public static void main(String args[])
    { 
        if(args.length == 0){
            System.out.println("usage: java client <port>");
            System.exit(1);
        }
        
        int port = isParseInt(args[0]);
        if(port == -1){
            System.out.println("usage: java client <port>");
            System.out.println("<port>: integer");
            System.exit(1);
        }
        
        try{
            //IP is hard coded
            //port is user entry
            Socket socket = new Socket("192.168.111.109", port);
            
            PrintWriter printWriter = 
                new PrintWriter(socket.getOutputStream(), true);
            printWriter.println(RQS_TEMP);
            
            InputStream inputStream = socket.getInputStream();
            
            ByteArrayOutputStream byteArrayOutputStream = 
                new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];

            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1){
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
                
            socket.close();
        
            System.out.println(byteArrayOutputStream.toString("UTF-8"));
            
        }catch(UnknownHostException e){
            System.out.println(e.toString());
        }catch(IOException e){
            System.out.println(e.toString());
        }

    }


    private static int isParseInt(String str){
        
        int num = -1;
        try{
             num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
        }
        
        return num;
    }
    
}

host.java
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class host {
    
    final static Integer RQS_DEFAULT = 0;
    final static Integer RQS_TEMP = 1;

    public static void main(String srgs[]) {

        int count = 0;

        //hard code to use port 8080
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            
            System.out.println("I'm waiting here: " + serverSocket.getLocalPort());
            
            while (true) {
                
                try {
                    Socket socket = serverSocket.accept();
                            
                    count++;
                    System.out.println("#" + count + " from "
                            + socket.getInetAddress() + ":" 
                            + socket.getPort());
                    
                    HostThread myHostThread = new HostThread(socket, count);
                    myHostThread.start();
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
    
    private static class HostThread extends Thread{
        
        private Socket hostThreadSocket;
        int cnt;
        
        HostThread(Socket socket, int c){
            hostThreadSocket = socket;
            cnt = c;
        }

        @Override
        public void run() {
            //
            Integer rqs = RQS_DEFAULT;
            try{
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(hostThreadSocket.getInputStream()));
                rqs =  new Integer(bufferedReader.readLine());
            }catch (IOException ex){
                Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            System.out.println("RQS = " + rqs);
            //
            
            String returnMsg;
            if(rqs.equals(RQS_DEFAULT)){
                returnMsg = "Hello from Raspberry Pi in background thread, you are #" + cnt;
            }else if(rqs.equals(RQS_TEMP)){
                returnMsg = ReadTemp() + "you are #" + cnt;
            }else{
                returnMsg = "unknown RQS! you are #" + cnt;
            }

            OutputStream outputStream;
            try {
                outputStream = hostThreadSocket.getOutputStream();
                
                try (PrintStream printStream = new PrintStream(outputStream)) {
                        printStream.print(returnMsg);
                }
            } catch (IOException ex) {
                Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
            }finally{
                try {
                    hostThreadSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    private static String ReadTemp(){
        String Temp = null;
        
        String[] command = {"vcgencmd", "measure_temp"};
        StringBuilder cmdReturn = new StringBuilder();
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();
            
            try (InputStream inputStream = process.getInputStream()) {
                int c;
                while ((c = inputStream.read()) != -1) {
                    cmdReturn.append((char) c);
                }
            }
            
            Temp = cmdReturn.toString();

        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
        
        return Temp;
    }
}



Download source code.



Java exercise - Implement client and server to communicate using Socket, step-by-step.

Read Raspberry Pi system temperature in Java

This exercise show how to read Pi's system temperature in Java, using ProcessBuilder with command of "vcgencmd measure_temp".

Read Raspberry Pi system temperature in Java
Read Raspberry Pi system temperature in Java

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Scanner;

/**
 * @web helloraspberrypi.blogspot.com
 */
public class readTemp {

    public static void main(String[] args) {

        // Example to run "dir" in Windows
        String[] command = {"vcgencmd", "measure_temp"};
        StringBuilder cmdReturn = new StringBuilder();
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();
            
            try (InputStream inputStream = process.getInputStream()) {
                int c;
                while ((c = inputStream.read()) != -1) {
                    cmdReturn.append((char) c);
                }
            }
            
            System.out.println(cmdReturn.toString());
            String stringTemp = measure_temp_toString(cmdReturn.toString());
            System.out.println("Get the numerical part as String: " + stringTemp);
            System.out.println("converte to float: " + cnvStringToFloat(stringTemp));

        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
        
    }
    
    private static String measure_temp_toString(String src){
        return src.replaceAll("[^0123456789.]", "");
    }
    
    private static float cnvStringToFloat(String src){

        float result = (float)0.0;
        Scanner scanner = new Scanner(src);
        while(scanner.hasNext()){
            if(scanner.hasNextFloat()){
                result = scanner.nextFloat();
            }else{
                scanner.next(); //ignore
            }
        }
        return result;
    }
    
}

Sunday, December 22, 2013

Communication between Android + Raspberry Pi

In previous post "Java exercise - Implement client and server to communicate using Socket", both host (implement ServerSocket and Socket) and client (implement Socket) are run on Raspberry Pi to setup communication between application via socket. Actually both the host and client can run on any PC with Java.

The client side in the post is ported to Android in this exercise, setup Socket in AsyncTask, to communicate with Raspberry Pi. The updated version of Host (run socket operation in background thread) run on Raspberry Pi or any other PC is here.

Implement Socket on Android to communicate with Raspberry Pi
Implement Socket on Android
MainActivity.java
package com.example.androidclient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 TextView textResponse;
 EditText editTextAddress, editTextPort; 
 Button buttonConnect, buttonClear;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  editTextAddress = (EditText)findViewById(R.id.address);
  editTextPort = (EditText)findViewById(R.id.port);
  buttonConnect = (Button)findViewById(R.id.connect);
  buttonClear = (Button)findViewById(R.id.clear);
  textResponse = (TextView)findViewById(R.id.response);
  
  buttonConnect.setOnClickListener(buttonConnectOnClickListener);
  
  buttonClear.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    textResponse.setText("");
   }});
 }
 
 OnClickListener buttonConnectOnClickListener = 
   new OnClickListener(){

    @Override
    public void onClick(View arg0) {
     /*
      * You have to verify editTextAddress and
      * editTextPort are input as correct format.
      */
     
     MyClientTask myClientTask = new MyClientTask(
       editTextAddress.getText().toString(),
       Integer.parseInt(editTextPort.getText().toString()));
     myClientTask.execute();
    }};

 public class MyClientTask extends AsyncTask<Void, Void, Void> {
  
  String dstAddress;
  int dstPort;
  String response;
  
  MyClientTask(String addr, int port){
   dstAddress = addr;
   dstPort = port;
  }

  @Override
  protected Void doInBackground(Void... arg0) {
   
   try {
    Socket socket = new Socket(dstAddress, dstPort);
    InputStream inputStream = socket.getInputStream();
    ByteArrayOutputStream byteArrayOutputStream = 
                  new ByteArrayOutputStream(1024);
    byte[] buffer = new byte[1024];
    
    int bytesRead;
             while ((bytesRead = inputStream.read(buffer)) != -1){
                 byteArrayOutputStream.write(buffer, 0, bytesRead);
             }
             
             socket.close();
             response = byteArrayOutputStream.toString("UTF-8");
    
   } catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return null;
  }

  @Override
  protected void onPostExecute(Void result) {
   textResponse.setText(response);
   super.onPostExecute(result);
  }
  
 }

}


Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    <EditText 
        android:id="@+id/address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="dstAddress" />
    <EditText 
        android:id="@+id/port"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="dstPort" />
    <Button 
        android:id="@+id/connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Connect..."/>
    <Button 
        android:id="@+id/clear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Clear"/>
    <TextView
        android:id="@+id/response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>


AndroidManifest.xml have to be modified to add <uses-permission android:name="android.permission.INTERNET"/>



download filesDownload the files.

or Download and install the APK file.



Cross-post with my another port Android-er.

Example of programming with java-gnome

Once installed libjava-gnome-java, we can prepare our "Hello World" using java-gnome. Basically it have the same function as "GTK+ exercise: GtkBox - A container box", a basic GTK+ Window with 3 Labels.

helloGnome
helloGnome
Edit helloGnome.java
import org.gnome.gtk.Gtk;
import org.gnome.gtk.Window;
import org.gnome.gtk.Widget;
import org.gnome.gdk.Event;
import org.gnome.gtk.Label;
import org.gnome.gtk.HBox;

public class helloGnome
{
    public static void main(String[] args) {
        final Window window;
        final HBox hBox;
        final Label label1, label2, label3;

        Gtk.init(args);

        window = new Window();
        window.setTitle("Hello Raspberry Pi - java-gnome exercise");
        window.connect(new Window.DeleteEvent() {
            public boolean onDeleteEvent(Widget source, Event event) {
                Gtk.mainQuit();
                return false;
            }
        });

        label1 = new Label("Label 1");
        label2 = new Label("Label 2");
        label3 = new Label("Label 3");

        hBox = new HBox(false, 3);
        hBox.add(label1);
        hBox.add(label2);
        hBox.add(label3);

        window.add(hBox);
        window.showAll();

        Gtk.main();
    }
}


Compile it with the command:
$ javac -classpath /usr/share/java/gtk-4.1.jar helloGnome.java

and run it:
$ java -classpath /usr/share/java/gtk-4.1.jar:. helloGnome

Install java-gnome on Raspberry Pi

java-gnome, currently 4.1, are the Java bindings for GTK and GNOME. Featuring a robust engineering design, completely generated internals, a lovingly crafted layer presenting the public API, and steadily increasing coverage of the underlying libraries.

You can use java-gnome to develop sophisticated user interfaces for Linux applications so that they richly integrate with the GNOME Desktop while leveraging the power of the Java language and your expertise with it.

To install java-gnome, enter the command:
$ sudo apt-get install libjava-gnome-java

Please notice that the file gtk-4.1.jar will be installed in /usr/share/java/, you will need it when compile and run the java using java-gnome.

/usr/share/java/gtk-4.1
/usr/share/java/gtk-4.1
Next:
Example of programming with java-gnome

Saturday, December 21, 2013

Java program with Swing GUI run on Raspberry Pi

This exercise create a hello.java with Swing GUI, develop and run on Raspberry Pi with JDK 8 Early Access Releases.

Java program with Swing GUI run on Raspberry Pi
Java program with Swing GUI run on Raspberry Pi
hello.java
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
 
/**
 * @web http://helloraspberrypi.blogspot.com/
 */
public class hello extends JFrame 
    implements ActionListener{
 
    JTextArea textArea;
    JButton buttonHello;
     
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
 
    private static void createAndShowGUI() {
        hello myFrame = new hello();
 
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         
        myFrame.prepareUI();
 
        myFrame.pack();
        myFrame.setVisible(true);
    }
     
    private void prepareUI(){
        textArea = new JTextArea();
        textArea.setEditable(false);
        JScrollPane panel = new JScrollPane(textArea);
        panel.setPreferredSize(new Dimension(300, 100));
         
        buttonHello = new JButton("Hello");
        buttonHello.addActionListener(this);
         
        getContentPane().add(panel, BorderLayout.CENTER);
        getContentPane().add(buttonHello, BorderLayout.PAGE_END);
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        textArea.setText("Hello from Raspberry Pi");
    }

}

Compile it:
$ javac hello.java

Run:
$ java hello



"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

Friday, December 20, 2013

Java exercise - Client and Server example III, run socket operation in background thread

This exercise implement socket operation of host in background thread, modify from last exercise, "ServerSocket stay in loop".

run socket operation in background thread
run socket operation in background thread
host.java
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class host {

    public static void main(String srgs[]) {

        int count = 0;

        //hard code to use port 8080
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            
            System.out.println("I'm waiting here: " + serverSocket.getLocalPort());
            
            while (true) {
                
                try {
                    Socket socket = serverSocket.accept();
                            
                    count++;
                    System.out.println("#" + count + " from "
                            + socket.getInetAddress() + ":" 
                            + socket.getPort());
                    
                    /*  move to background thread
                    OutputStream outputStream = socket.getOutputStream();
                    try (PrintStream printStream = new PrintStream(outputStream)) {
                        printStream.print("Hello from Raspberry Pi, you are #" + count);
                    }
                    */
                    HostThread myHostThread = new HostThread(socket, count);
                    myHostThread.start();
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
    
    private static class HostThread extends Thread{
        
        private Socket hostThreadSocket;
        int cnt;
        
        HostThread(Socket socket, int c){
            hostThreadSocket = socket;
            cnt = c;
        }

        @Override
        public void run() {

            OutputStream outputStream;
            try {
                outputStream = hostThreadSocket.getOutputStream();
                
                try (PrintStream printStream = new PrintStream(outputStream)) {
                        printStream.print("Hello from Raspberry Pi in background thread, you are #" + cnt);
                }
            } catch (IOException ex) {
                Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
            }finally{
                try {
                    hostThreadSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


Keep using the client.java in last exercise of "client and server to communicate using Socket".

Tuesday, December 17, 2013

Linux tips: run and kill process in background

To start a process and force it run in background, add the character '&' after the command:
$ [cmd] [args] &

To lists the jobs that you are running in the background, enter the command:
$ jobs

To kill a job running in background, using the kill command.

The video demo how it work on Raspberry Pi. A lxtask is open to monitor the running process. And two terminal are opened to run host (on right side) and client (on bottom-left). The host program is a long-running program. The client program send request to host. To know more about it, read the post "Java exercise - Client and Server example II, ServerSocket stay in loop". The video show how to run the host program in background.


Java exercise - Client and Server example II, ServerSocket stay in loop

In the previous exercise of "client and server to communicate using Socket", the host.java stay waiting request from client.java, and terminate after responsed. In this step, it's modified to stay in loop, for next request; until user press Ctrl+C to terminate the program.

host stey in loop
host stey in loop, until Ctrl+C.

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class host {

    public static void main(String srgs[]) {

        int count = 0;

        //hard code to use port 8080
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            System.out.println("I'm waiting here: " 
                + serverSocket.getLocalPort());
            
            System.out.println(
                "This program will stay monitoring port 80.");
            System.out.println(
                "Until user press Ctrl+C to terminate.");
            
            while (true) {
                try (Socket socket = serverSocket.accept()) {
                    count++;
                    System.out.println("#" + count + " from "
                            + socket.getInetAddress() + ":" 
                            + socket.getPort());
                    OutputStream outputStream = socket.getOutputStream();
                    try (PrintStream printStream = 
                        new PrintStream(outputStream)) {
                            printStream.print(
                                "Hello from Raspberry Pi, you are #" 
                                + count);
                    }
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
}

Keep using the client.java in last exercise of "client and server to communicate using Socket".



Next exercise: - Client and Server example III, run socket operation in background thread.

Develop Java application in Windows, run in Raspberry Pi.

This post show Java application developed jar in Windows using Netbeans IDE, can be run on both Windows and Raspberry Pi.

Java jar run on Windows and Raspberry Pi
Java jar run on Windows and Raspberry Pi
Both Raspberry Pi and Windows 8.1 have the same JDK™ 8 Early Access Releases installed; JDK for Windows 32-bit on Windows, JDK of Linux ARMv6/7 VFP, HardFP ABI on Raspberry Pi.

demo video:

The code used here as a example can be found in "List system properties using java",  to list available system properties.

- Start Netbeans IDE in Windows, new a Java Application.

- Make sure it target the same Java platform running in Pi side. Right click on Project > Properties > Category of Libraries > Select Java Platform of JDK 1.8.

- Edit, and build your application.

- To know where is the generated jar, click Run > Clean and Build. The generated jar wil be in "Created dir: <...>\JavaTest\dist".

- Copy the generated jar, JavaTest.jar, to Raspberry Pi.

- Run it in Raspberry Pi side by enter:
java -jar JavaTest.jar


Updated:
- Remote run Java on Raspberry Pi, host from NetBeans on Windows 10

Monday, December 16, 2013

Tontec 2.4-inch TFT LCD 240x320 RGB Pixels Touch Screen Display Monitor For Raspberry Pi

Tontec 2.4-inch TFT LCD 240x320 RGB Pixels Touch Screen Display Monitor For Raspberry Pi

- This Raspberry Pi Screen is designed for raspberry pi tailored a expansion board, set LCD, touch, IO expansion, RTC functions in one, greatly enriched the raspberry pie can learn playability.

- "Display Part" use Hitachi's IPS technology company of the LCD, the screen viewing angle is large, close to 180 degrees; very high brightness and contrast, color of the screen is 8,16 I80 parallel, in order to save resources and high-speed IO the transmission of data, the owner after two months of struggle with CPLD design a SPI-I80 parallel converter, the measured SPI clock can reach 120M.

- "Touch Part" adopts TI (Texas Instruments) company TSC2003 chip, the chip I2C Interface 4-wire resistive controller, also with a 2-way BAT and AIN, can monitor 2-way 2-way voltage and other signals.

- "IO extension Part" using NS (National Semiconductor)'s LP3943, the I2C interface chip 16 IO expansion, which with the PWM circuit can drive the LED.

- "RTC real time clock" using NXP's PCF8563, the chip I2C interface, with a calendar. (This section is optional, standard shipping is blank, the customer can DIY)


  • Size: 2.4 inches
  • Color: 65K colors
  • Resolution: QVGA 240X320
  • Back light: 3 LED Parallel
  • Interface: SIP16, 8-pin 2.54mm single row




Related:
- Setup Tontec 2.4-inch TFT LCD 240x320 RGB Pixels Touch Screen Display Monitor For Raspberry Pi

Sunday, December 15, 2013

Java exercise - Implement client and server to communicate using Socket, step-by-step

This examples create two separated program (host and client) with Java, using java.net.Socket.

In host side, it start ServerSocket and wait for client. In client side, the IP address of host is hard coded, user have to enter port number of host manually. Once connected, the host will send a message to client and exit the program.

Implement host and client to communicate using Socket
Implement Java host and client to communicate using Socket
In the demo video on bottom of this post, the host run on Raspberry Pi, the client run on the same Raspberry Pi, and run on another PC running Windows 8.1.

host.java
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.IOException;

class host
{
    public static void main(String srgs[])
    {   
        try{
            ServerSocket serverSocket = new ServerSocket(0);
            System.out.println("I'm waiting here: " + serverSocket.getLocalPort());            
                                
            Socket socket = serverSocket.accept();
            System.out.println("from " + 
                socket.getInetAddress() + ":" + socket.getPort());
            
            OutputStream outputStream = socket.getOutputStream();
            PrintStream printStream = new PrintStream(outputStream);
            printStream.print("Hello Raspberry Pi");
            printStream.close();
            
            socket.close();
        }catch(IOException e){
            System.out.println(e.toString());
        }
        
    }
}


client.java
import java.net.Socket;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;

class client{

    public static void main(String args[])
    { 
        if(args.length == 0){
            System.out.println("usage: java client <port>");
            System.exit(1);
        }
        
        int port = isParseInt(args[0]);
        if(port == -1){
            System.out.println("usage: java client <port>");
            System.out.println("<port>: integer");
            System.exit(1);
        }
        
        try{
            //IP is hard coded
            //port is user entry
            Socket socket = new Socket("192.168.111.108", port);
            InputStream inputStream = socket.getInputStream();
            
            ByteArrayOutputStream byteArrayOutputStream = 
                new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];

            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1){
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
                
            socket.close();
        
            System.out.println(byteArrayOutputStream.toString("UTF-8"));
            
        }catch(UnknownHostException e){
            System.out.println(e.toString());
        }catch(IOException e){
            System.out.println(e.toString());
        }

    }


    private static int isParseInt(String str){
        
        int num = -1;
        try{
             num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
        }
        
        return num;
    }
    
}




Download Java code of host.java and client.java.

Step-by-step:

Find a free port using Java with ServerSocket(0)

Use the constructor ServerSocket(int port) of java.net.ServerSocket class with 0 to request a free port automatically, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

Example:
import java.net.ServerSocket;
import java.io.IOException;

class checkSocket
{
    public static void main(String srgs[])
    {
        System.out.println("Hello Raspberry Pi");
        
        try{
            ServerSocket socket0 = new ServerSocket(0);
            System.out.println("Automatically allocated port: " 
                                + socket0.getLocalPort());
        }catch(IOException e){
            System.out.println(e.toString());
        }
        
    }
}

Find a free port using Java with ServerSocket(0)
Find a free port using Java with ServerSocket(0)

Saturday, December 14, 2013

Friday, December 13, 2013

Install and program with GTK+ 3.0 in Python

To program Python with GTK+ 3.0, libgtk-3-dev have to be installed:
$ sudo apt-get install libgtk-3-dev
(referene: Install GTK+ 3.0 on Raspberry Pi)

Once installed, Python 2 (python and IDLE) can work use GTK+ 3.0 library to programming with GUI.

Dummy example of Python program with GTK+ 3.0
#!/usr/bin/python
from gi.repository import Gtk

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

"Hello World" of Python 2.7.3 with GTK+ 3
"Hello World" of Python 2.7.3 with GTK+ 3
To work with Python 3, python3-gi is needed. Otherwise will have ImportError of "No module named gi.repository". To install python3-gi, enter command:
sudo apt-get install python3-gi

ImportError: No module named gi.repository
ImportError: No module named gi.repository

"Hello World" of Python 3.2.3 with GTK+ 3
"Hello World" of Python 3.2.3 with GTK+ 3

The Python GTK+ 3 Tutorial gives an introduction to writing GTK+ 3 applications in Python.

Raspberry Pi Cookbook: Finding your way around the GPIO connector

Learn what does what on the GPIO connector of Raspberry Pi board.



Thursday, December 12, 2013

Programming an Arduino from Raspberry Pi

Learn how to install the Arduino IDE on your Raspberry Pi so that you can write and upload programs onto an Arduino.



Raspberry Pi Cookbook

Raspberry Pi Cookbook
Raspberry Pi Cookbook
Raspberry Pi Cookbook
The world of Raspberry Pi is evolving quickly, with many new interface boards and software libraries becoming available all the time. In this cookbook, prolific hacker and author Simon Monk provides more than 200 practical recipes for running this tiny low-cost computer with Linux, programming it with Python, and hooking up sensors, motors, and other hardware—including Arduino.
You’ll also learn basic principles to help you use new technologies with Raspberry Pi as its ecosystem develops. Python and other code examples from the book are available on GitHub. This cookbook is ideal for programmers and hobbyists familiar with the Pi through resources such as Getting Started with Raspberry Pi (O’Reilly).
  • Set up and manage your Raspberry Pi
  • Connect the Pi to a network
  • Work with its Linux-based operating system
  • Use the Pi’s ready-made software
  • Program Raspberry Pi with Python
  • Control hardware through the GPIO connector
  • Use Raspberry Pi to run different types of motors
  • Work with switches, keypads, and other digital inputs
  • Hook up sensors for taking various measurements
  • Attach different displays, such as an LED matrix
  • Create dynamic projects with Raspberry Pi and Arduino

Wednesday, December 11, 2013

Run system command and read output using Java

The exercise run system command with StringBuilder(), and read the output with InputStream.

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @org java-buddy.blogspot.com
 * @web helloraspberrypi.blogspot.com
 */
public class df {

    public static void main(String[] args) {

        // Example to run "dir" in Windows
        String[] command = {"df", "-h", "/"};
        StringBuilder cmdReturn = new StringBuilder();
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();
            
            try (InputStream inputStream = process.getInputStream()) {
                int c;
                while ((c = inputStream.read()) != -1) {
                    cmdReturn.append((char) c);
                }
            }
            System.out.println(cmdReturn.toString());

        } catch (IOException ex) {
            Logger.getLogger(df.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
        
    }
    
}

Run system command and read output using Java

The code from Java-Buddy: ProcessBuilder to create operating system processes

Related: Read Pi's system temperature in Java, using ProcessBuilder with command of "vcgencmd measure_temp".

GTK+ C example with GUI created using Glade

This post show how to create GUI using Glade, and link the generated glade file in c code, then compile with gcc with GTK+ 3.0, to generate a executable program.


- Start glade, create something. Specify the window in TOPLEVEL with name "myname". Save as "testGlade.glade". We will refer them in our c code.

Create GUI with Glade
- Create our c source code, "test.c".
#include <gtk/gtk.h>

int main(int argc, char *argv[])
{
    GtkBuilder *gtkBuilder;
    GtkWidget *window;
    gtk_init(&argc, &argv);
    
    gtkBuilder = gtk_builder_new();
    gtk_builder_add_from_file(gtkBuilder, "testGlade.glade", NULL);
    window = GTK_WIDGET(gtk_builder_get_object(gtkBuilder, "mywindow"));
    
    g_object_unref(G_OBJECT(gtkBuilder));
    gtk_widget_show(window);
    gtk_main();
    
    return 0;
}

where "mywindow" is the window defined in Glade. And "testGlade.glade" is our saved glade file.

- Compile it with command:
$ gcc -Wall -g -o testGlade test.c `pkg-config --cflags --libs gtk+-3.0`

Where testGlade is the target executable file. Run it:
$ ./testGlade

Because we have do nothing on the code. The program just show a menu bar without action.





Remark:

It's commented to use following command:
gcc -Wall -g -o testGlade test.c $(pkg-config --cflags gtk+-3.0) $(pkg-config --libs gtk+-3.0)

~ thx teknikkim

Install Glade on Raspberry Pi

Glade is a RAD tool to enable quick & easy development of user interfaces for the GTK+ toolkit and the GNOME desktop environment.

The user interfaces designed in Glade are saved as XML, and by using the GtkBuilder GTK+ object these can be loaded by applications dynamically as needed.

By using GtkBuilder, Glade XML files can be used in numerous programming languages including C, C++, C#, Vala, Java, Perl, Python,and others.


To install Glade on Raspberry Pi, enter the command:
sudo apt-get install glade

Glade on Raspberry Pi
Glade on Raspberry Pi


Once installed, it can be found in Raspberry Pi desktop Start button > Programming > Glade. Or enter glade directly on Terminal.

The next post show how to link Glade file in c code, and compile a executable program.

Tuesday, December 10, 2013

GTK+ exercise: GtkBox - A container box

Example of using GtkBox.
GtkBox
Example of using GtkBox
helloGtkBox.c
#include <gtk/gtk.h>

int main(int argc, char *argv[])
{
    GtkWidget *window;
    GtkWidget *label1, *label2, *label3;
    GtkWidget *box;
    
    gtk_init(&argc, &argv);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    
    gtk_window_set_title(GTK_WINDOW(window), 
        "Hello Raspberry Pi - GTK+ exercise"); 
        
    //terminate the application when the GtkWindow is destroyed
    g_signal_connect (window, "destroy", 
        G_CALLBACK(gtk_main_quit), NULL);
    
    label1 = gtk_label_new("Label 1");
    label2 = gtk_label_new("Label 2");
    label3 = gtk_label_new("Label 3");
    
    box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
    
    gtk_box_pack_start(GTK_BOX(box), label1, TRUE, FALSE, 5);
    gtk_box_pack_start(GTK_BOX(box), label2, TRUE, FALSE, 5);
    gtk_box_pack_start(GTK_BOX(box), label3, TRUE, FALSE, 5);
    
    gtk_container_add(GTK_CONTAINER(window), box);
    gtk_widget_show_all(window);
    
    gtk_main();
    
    return 0;
}


Use Remmina (remote desktop client) from Linux to log-in Raspberry Pi xrdp server

In previous posts, it show how to "install xrdp (X Remote Desktop Protocol) on Raspberry Pi and log-in from Windows using Remote Desktop Connection" and "log-in from Android using Microsoft Remote Desktop app". We can also log-in from Linux with Remmina (remote desktop client).

If you are running Ubuntu, may be you already have Remmina installed. If not, install with the command:
$ sudo apt-get install remmina

and run it with 

$ remmina




2.4GHz Wireless Entertainment Keyboard with Touchpad

Hausbell ® Mini H7 2.4GHz Wireless Entertainment Keyboard with Touchpad for PC, Pad, Andriod TV Box, Google TV Box, Xbox360, PS3 & HTPC/IPTV
Quickview: 
This is a wonderful combo, 2.4GHz Mini Wireless QWERTY keyboard, TouchPad combo, with USB interface adapter for the lectuer, sales manager, presenter and others, from within a 15' radius make a presentation and operate PC wirelessly. Change slides and screen options, write on the screen, emphasize words and objects just by using this wireless mini keyboard and mouse with touchpad. Perfect for PC, Pad, Andriod TV Box, Google TV Box, etc. 

Features: 
92 keys, 2.4GHz wireless Keyboard with Touchpad. 
Touchpad DPI adjustable functions. 
Built-in high sensitive smart touchpad with 360-degree flip design. 
Mini QWERTY keyboard with multimedia control keys and PC gaming control keys. 
Auto sleep and auto wake mode. 
Innovative shape, protable, elegant. 
The Ergonomically handheld design is easy to carry and operate. 
Build-in removable rechargable Li-ion battery that has longer standby time. 
Perfect for PC, Pad, Andriod TV Box, Google TV Box, for Xbox360, for PS3, HTPC/IPTV, etc. 

Specification: 
Operating range: 15 meters(MAX), without signal disturbance and no direction limit. 
Frequency range: 2.403GHZ ~ 2.480GHZ 
Operational voltage: 3.3V 
Charge Voltage: 4.4V ~ 5.25V 
Modulation: GFSK 
Channel: 78channels 
TX Power: less than +5dBm 
Transmission rate: 1M bit/sec 
Frequency tolerance: +/-30ppm 
Power consumption: 55mA(on), 1mA(sleep) 
Color:Black 
Battery Type: Built-in lithium-ion battery 
Notice: After 3 minutes without any operating will into sleep mode, press any key about 1s to wake up. 

Package including: 
1 * Wireless keyboard 
1 * Wireless receiver 
1 * Charging data cable 
1 * User manual 
Note:If your device without USB 2.0 jack(Plug the Wireless receiver),you need buy one.