Friday, September 19, 2014

Display CPU Frequency monitor on Raspberry Pi Task Bar

To enable CPUFreq frontend applet on your Raspberry Pi taskbar to monitor CPU frequency:




  • Right click Task Bar
  • Select Add/Remove Panel Items
  • Select CPU Usage Monitor, click Add.
  • CPUFreq frontend, click Add.

CPUFreq frontend applet will be added on your Task Bar. To monitor your CPU frequency, move mouse hover over the CPUFreq frontend applet.


HummingBoard Vs Raspberry Pi


Learn more about HummingBoard: http://www.solid-run.com/products/hummingboard/

High Performance Python: Practical Performant Programming for Humans



High Performance Python: Practical Performant Programming for Humans

Your Python code may run correctly, but you need it to run faster. By exploring the fundamental theory behind design choices, this practical guide helps you gain a deeper understanding of Python’s implementation. You’ll learn how to locate performance bottlenecks and significantly speed up your code in high-data-volume programs.

How can you take advantage of multi-core architectures or clusters? Or build a system that can scale up and down without losing reliability? Experienced Python programmers will learn concrete solutions to these and other issues, along with war stories from companies that use high performance Python for social media analytics, productionized machine learning, and other situations.
  • Get a better grasp of numpy, Cython, and profilers
  • Learn how Python abstracts the underlying computer architecture
  • Use profiling to find bottlenecks in CPU time and memory usage
  • Write efficient programs by choosing appropriate data structures
  • Speed up matrix and vector computations
  • Use tools to compile Python down to machine code
  • Manage multiple I/O and computational operations concurrently
  • Convert multiprocessing code to run on a local or remote cluster
  • Solve large problems while using less RAM

Tuesday, September 16, 2014

Monday, September 15, 2014

Web control to display on Pi connected LCD Module, with Python and bottle

This post show how to build a simple web application on Raspberry Pi using Python + bottle, receive POST from client to display message on connected 2x16 LCD Module.


To install python-bottle on Raspberry Pi, refer to the post "Python + bottle@Raspberry Pi: Web based GPIO control".

The previouse post "2x16 LCD Display on Raspberry Pi" show how to connect and text 2x16 LCD Module on Raspberry Pi. To control the LCD Module with Python, the program Adafruit_CharLCD.py in the post is needed.

weblcd.py
from bottle import route, run
from bottle import post, request

from Adafruit_CharLCD import Adafruit_CharLCD
lcd = Adafruit_CharLCD()

host = '192.168.1.105'

@route('/')
def index():
    return '''
        <form action="/" method="post">
            Hello: <input name="msg" type="text" />
            <input value="post" type="submit" />
        </form>
    '''

@route('/', method='POST')
def do_msg():
    msg = request.forms.get('msg')
    lcd.clear()
    lcd.message(msg)
    return index()

lcd.clear()
lcd.message("Hello:\n Raspberry Pi")

run(host=host, port=80)

Download HERE.

2x16 LCD Display on Raspberry Pi

This post show how to connect 2x16 LCD Display Module (come from another Arduino starter kit) to Raspberry Pi, and test it with Python.


How to connect 2x16 LCD Display Module to Raspberry Pi:


Visit GitHib of adafruit/Adafruit-Raspberry-Pi-Python-Code/Adafruit_CharLCD. There is a sample Python code to drive 2x16 CharLCD on Raspberry Pi, Adafruit_CharLCD.py.

For Raspberry Pi Model B, rev 2, change pin 21 to 27:
Search the code:
    def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, 21, 22], GPIO=None):

to:
    def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, 27, 22], GPIO=None):

Run it with sudo, to display welcome message of " Adafruit 16x2\n Standard LCD".

$ sudo python Adafruit_CharLCD.py

Another sample code Adafruit_CharLCD_IPclock_example.py, display datetime and the IP of your Raspberry Pi.

$ sudo python Adafruit_CharLCD_IPclock_example.py

Both sampls can be download Here.

Related:
- Web control to display on Pi connected LCD Module, with Python and bottle

Sunday, September 14, 2014

Control Raspberry Pi GPIO using C language

This example show how to control GPIO (pin 18 in this example) using C language.



testPin.c
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>

#define BCM2708_PERI_BASE   0x20000000
#define GPIO_BASE           (BCM2708_PERI_BASE + 0x200000) /* GPIO controller */

#define LED_18              18

#define BLOCK_SIZE (4*1024)

int mem_fd;
void *gpio_map;
volatile unsigned *gpio;

// GPIO setup macros. Always use INP_GPIO(x) before using OUT_GPIO(x) or SET_GPIO_ALT(x,y)
#define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3))
#define OUT_GPIO(g) *(gpio+((g)/10)) |=  (1<<(((g)%10)*3))
#define SET_GPIO_ALT(g,a) *(gpio+(((g)/10))) |= (((a)<=3?(a)+4:(a)==4?3:2)<<(((g)%10)*3))

#define GPIO_SET *(gpio+7)  // sets   bits which are 1 ignores bits which are 0
#define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0
 
int init_io()
{
    /* open /dev/mem */
    if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
        printf("can't open /dev/mem \n");
        return(-1);
    }else{
        printf("/dev/mem opened\n");
        
        /* mmap GPIO */
        gpio_map = mmap(
            NULL,             //Any adddress in our space will do
            BLOCK_SIZE,       //Map length
            PROT_READ|PROT_WRITE,// Enable reading & writting to mapped memory
            MAP_SHARED,       //Shared with other processes
            mem_fd,           //File to map
            GPIO_BASE         //Offset to GPIO peripheral   
        );
        
        close(mem_fd);
        printf("/dev/mem closed\n");
        
        if (gpio_map == MAP_FAILED) {
            printf("mmap error %d\n", (int)gpio_map);//errno also set!
            return(-1);
        }else{
            printf("mmap Success.\n");
        }
        
    }
    
    // Always use volatile pointer!
   gpio = (volatile unsigned *)gpio_map;

   return 0;
}


int main(){
    
    if(init_io() == -1) 
    {
        printf("Failed to map the physical GPIO registers into the virtual memory space.\n");
        return -1;
    }
    
    // must use INP_GPIO before we can use OUT_GPIO
    INP_GPIO(LED_18); 
    OUT_GPIO(LED_18);
    
    int repeat;
    for (repeat=1; repeat<5; repeat++)
    {
        GPIO_CLR = 1 << LED_18;
        printf("LED OFF\n");
        sleep(2);

        GPIO_SET = 1 << LED_18;
        printf("LED ON\n");
        sleep(1);
    }
    
    printf("- finished -\n");
    return 0;
}

Download HERE.

Compile with:
$ gcc testPin.c

Run with sudo:
$ sudo ./a.out


Python + bottle@Raspberry Pi: Web based GPIO control

This example show how to program in Python with bottle on Raspberry Pi, to implement web base GPIO control.

bottle is a Python web server library. To install bottle on Raspberry Pi, enter the command:
sudo apt-get install python-bottle


Create webled.py
from bottle import route, run
import RPi.GPIO as GPIO

host = '192.168.1.105'

pinButton = 17
pinLed = 18
GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(pinButton, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(pinLed, GPIO.OUT)

LedState = False

def read_button():
    if GPIO.input(pinButton):
        return 'Released'
    else:
        return 'Pressed'

def update_led():
    GPIO.output(pinLed, LedState)
    
def toggleLed():
    global LedState
    LedState = not LedState
    
@route('/')
@route('/<arg>')
def index(arg=""):
    if arg == "toggle":
        toggleLed()
        
    update_led()
    
    response = "<html>\n"
    response += "<body>\n"
    response += "<script>\n"
    response += "function changed()\n"
    response += "{window.location.href='/toggle'}\n"
    response += "</script>\n"
    
    response += "Button: " + read_button() +"\n"
    response += "<br/><br/>\n"
    response += "<input type='button' onClick='changed()' value=' LED '/>\n"
    response += "</body></html>\n"
    return response
    
run(host=host, port=80)

Run it:
$ sudo python webled.py



Related:
- Web control to display on Pi connected LCD Module, with Python and bottle

Python RPi.GPIO: Read Button using GPIO.add_event_detect() with callback

The example show how to detect events of GPIO, to detect button pressed/released. It have the same operation in the post "Python RPi.GPIO: Button and LED".



import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(18, GPIO.OUT)

def ButtonCallback(channel):
    if (GPIO.input(17)):
        GPIO.output(18, False)
    else:
        GPIO.output(18, True)
    
GPIO.add_event_detect(17, GPIO.BOTH, callback=ButtonCallback);

while(True):
    #do nothing
    time.sleep(1)

Friday, September 12, 2014

Learn about physical computing with Raspberry Pi

New Raspbian (and NOOBS) available

New release (2014-09-09) of Raspbian, and also New Out Of the Box Software (NOOBS), available.

  • New firmware with various fixes and improvements
  • Minecraft Pi pre-installed
  • Sonic Pi upgraded to 2.0
  • Include Epiphany browser work from Collabora
  • Switch to Java 8 from Java 7
  • Updated Mathematica
  • Misc minor configuration changes

Download: http://www.raspberrypi.org/downloads/


Python RPi.GPIO: Button and LED

This example read button input from pin 17 (set as input with pull-up resister) and set output to pin 18 to turn ON/OFF LED accordingly.



The code GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) set pin 17 as input with pull-up resistor. If you omit the option pull_up_down=GPIO.PUD_UP, the pin will have no pull-up resistor, and become un-stable.

led.py
import RPi.GPIO as GPIO


GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(18, GPIO.OUT)

while(True):
 if (GPIO.input(17)):
  GPIO.output(18, False)
 else:
  GPIO.output(18, True)


Next:
Read Button using GPIO.add_event_detect() with callback

Wednesday, September 10, 2014

Raspberry Pi Python exercise: Change GPIO LED brightness with GPIO.PWM

Example of Python on Raspberry Pi, to change GPIO LED brightness with GPIO.PWM.



led.py
import RPi.GPIO as GPIO
import time

led_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)

#frequency 500 Hz
led_pwm = GPIO.PWM(led_pin, 500)
#duty cycle = 100
led_pwm.start(100)

while(True):
    led_pwm.ChangeDutyCycle(100)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(80)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(60)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(40)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(20)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(0)
    time.sleep(1)


Connection, check lst post of "Toggle LED on GPIO".

Raspberry Pi Python exercise: Toggle LED on GPIO

Python example run on Raspberry Pi, to toggle GPIO pin for LED.

connection:

Example code, led.py:
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

while(True):
    GPIO.output(18, True)
    time.sleep(1.5)
    GPIO.output(18, False)
    time.sleep(0.5)


Run it with sudo:
$ sudo python led.py

Next:
Change GPIO LED brightness with GPIO.PWM

Saturday, September 6, 2014

Yahoo Weather on Raspberry Pi, with text-to-speech

With java-google-translate-text-to-speech, we can add text-to-speech (tts) to previous Yahoo Weather exercise.


Java code on Raspberry Pi.
package java_jssc_uno;

import com.gtranslate.Audio;
import com.gtranslate.Language;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javazoom.jl.decoder.JavaLayerException;
import jssc.SerialPort;
import jssc.SerialPortException;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class Java_jSSC_Uno {

    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("/dev/ttyACM0");
        try {
            System.out.println("Port opened: " + serialPort.openPort());

            try {
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
            }

            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Java_jSSC_Uno".getBytes()));
            //System.out.println("Port closed: " + serialPort.closePort());
        } catch (SerialPortException ex) {
            System.out.println(ex);
        }

        YahooWeather yahooWeather = new YahooWeather();
        yahooWeather.queryWeather();
        
        MyWeather myYahooWeatherResult = yahooWeather.getWeatherResult();
        System.out.println(myYahooWeatherResult.toString());
        
        Reporter reporter = new Reporter(serialPort, myYahooWeatherResult);
        reporter.report();
        
        try {
            System.out.println("Port closed: " + serialPort.closePort());
        } catch (SerialPortException ex) {
            Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

class Reporter{
    SerialPort serialPort;
    MyWeather myWeather;
    
    Reporter(SerialPort serialPort, MyWeather myWeather){
        this.serialPort = serialPort;
        this.myWeather = myWeather;
    }
    
    public void report(){
        reportWord(myWeather.description);
        //reportWord(myWeather.city);
        //reportWord(myWeather.region);
        //reportWord(myWeather.country);
        reportWord(myWeather.conditiondate);
        
        reportWord("humidity: " + myWeather.humidity);
        reportWord("visibility: " + myWeather.visibility);
        reportWord("pressure: " + myWeather.pressure);
        reportWord("rising: " + myWeather.rising);
        
        reportWord("Wind chill: " + myWeather.windChill);
        reportWord("direction: " + myWeather.windDirection);
        reportWord("speed: " + myWeather.windSpeed);
        reportWord("Sunrise: " + myWeather.sunrise);
        reportWord("Sunset: " + myWeather.sunset);
        reportWord(myWeather.conditiontext);

    }
    
    private void reportWord(String word){
        try {
            serialPort.writeBytes(word.getBytes());
        } catch (SerialPortException ex) {
            Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
        }
        speak(word);
        delay2s();
    }
    
    private void speak(String word){
        Audio audio = Audio.getInstance();
        InputStream sound;
        try {
            sound = audio.getAudio(word, Language.ENGLISH);
            audio.play(sound);
        } catch (IOException | JavaLayerException ex) {
            Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

    private void delay2s(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}

class MyWeather{
    String description;
    String city;
    String region;
    String country;
    
    String windChill;
    String windDirection;
    String windSpeed;
    
    String humidity;
    String visibility;
    String pressure;
    String rising;
    
    String sunrise;
    String sunset;
    
    String conditiontext;
    String conditiondate;
    
    @Override
    public String toString(){
        
        return "\n- " + description + " -\n\n" 
            + "city: " + city + "\n"
            + "region: " + region + "\n"
            + "country: " + country + "\n\n"

            + "Wind\n"
            + "chill: " + windChill + "\n"
            + "direction: " + windDirection + "\n"
            + "speed: " + windSpeed + "\n\n"
            
            + "humidity: " + humidity + "\n"
            + "visibility: " + visibility + "\n"
            + "pressure: " + pressure + "\n"
            + "rising: " + rising + "\n\n"
            
            + "Sunrise: " + sunrise + "\n"
            + "Sunset: " + sunset + "\n\n"
            
            + "Condition: " + conditiontext + "\n"
            + conditiondate +"\n";
    }
}

class YahooWeather {
    
    MyWeather weatherResult;
    
    public void queryWeather(){
        String weatherString = query();
        Document weatherDoc = convertStringToDocument(weatherString);
        
        weatherResult = parseWeather(weatherDoc);
    }

    private String query() {
        String qResult = "";
        //Yahoo Weather Query URL for New York
        String queryString = "http://weather.yahooapis.com/forecastrss?w=2459115";

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(queryString);

        try {
            HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Reader in = new InputStreamReader(inputStream);
                BufferedReader bufferedreader = new BufferedReader(in);
                StringBuilder stringBuilder = new StringBuilder();

                String stringReadLine;

                while ((stringReadLine = bufferedreader.readLine()) != null) {
                    stringBuilder.append(stringReadLine).append("\n");
                }

                qResult = stringBuilder.toString();

            }

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

        return qResult;
    }

    private Document convertStringToDocument(String src) {
        Document doc = null;

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser;

        try {
            parser = dbFactory.newDocumentBuilder();
            doc = parser.parse(new ByteArrayInputStream(src.getBytes()));
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(YahooWeather.class.getName()).log(Level.SEVERE, null, ex);
        }

        return doc;
    }

    private MyWeather parseWeather(Document srcDoc){
        
        MyWeather myWeather = new MyWeather();

        //<description>Yahoo! Weather for New York, NY</description>
        myWeather.description = srcDoc.getElementsByTagName("description")
            .item(0)
            .getTextContent();

        //<yweather:location city="New York" region="NY" country="United States"/>
        Node locationNode = srcDoc.getElementsByTagName("yweather:location").item(0);
        myWeather.city = locationNode.getAttributes()
            .getNamedItem("city")
            .getNodeValue();
        
        myWeather.region = locationNode.getAttributes()
            .getNamedItem("region")
            .getNodeValue();
        
        myWeather.country = locationNode.getAttributes()
            .getNamedItem("country")
            .getNodeValue();

        //<yweather:wind chill="60" direction="0" speed="0"/>
        Node windNode = srcDoc.getElementsByTagName("yweather:wind").item(0);
        myWeather.windChill = windNode.getAttributes()
            .getNamedItem("chill")
            .getNodeValue();
        
        myWeather.windDirection = windNode.getAttributes()
            .getNamedItem("direction")
            .getNodeValue();
        
        myWeather.windSpeed = windNode.getAttributes()
            .getNamedItem("speed")
            .getNodeValue();
        
        //<yweather:atmosphere humidity="82" visibility="6" pressure="30.2" rising="0"/>
        Node atmosphereNode = srcDoc.getElementsByTagName("yweather:atmosphere").item(0);
        myWeather.humidity = atmosphereNode.getAttributes()
            .getNamedItem("humidity")
            .getNodeValue();
        
        myWeather.visibility = atmosphereNode.getAttributes()
            .getNamedItem("visibility")
            .getNodeValue();
        
        myWeather.pressure = atmosphereNode.getAttributes()
            .getNamedItem("pressure")
            .getNodeValue();
        
        myWeather.rising = atmosphereNode.getAttributes()
            .getNamedItem("rising")
            .getNodeValue();

        //<yweather:astronomy sunrise="6:52 am" sunset="7:10 pm"/>
        Node astronomyNode = srcDoc.getElementsByTagName("yweather:astronomy").item(0);
        myWeather.sunrise = astronomyNode.getAttributes()
            .getNamedItem("sunrise")
            .getNodeValue();
        
        myWeather.sunset = astronomyNode.getAttributes()
            .getNamedItem("sunset")
            .getNodeValue();

        //<yweather:condition text="Fair" code="33" temp="60" date="Fri, 23 Mar 2012 8:49 pm EDT"/>
        Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
        myWeather.conditiontext = conditionNode.getAttributes()
            .getNamedItem("text")
            .getNodeValue();
        
        myWeather.conditiondate = conditionNode.getAttributes()
            .getNamedItem("date")
            .getNodeValue();

        return myWeather;
    }
    
    public MyWeather getWeatherResult(){
        return weatherResult;
    }
    
    @Override
    public String toString(){
        return weatherResult.toString();
    }
}

Download HERE.

Keep using the sketch in the post "Read from Arduino Serial port, and write to 2x16 LCD" on Arduino Uno.

java-google-translate-text-to-speech, unofficial API for Google Translate in Java.

java-google-translate-text-to-speech is API unofficial with the main features of Google Translate in Java. I will add text-to-speech (tts) function in my next Yahoo Weather exercise.

This video show how to download jars, and add library to Netbeans Java project.

Install espeak, Text to Speech (Speech Synthesis), on Raspberry Pi

eSpeak is a compact open source software speech synthesizer for English and other languages, for Linux and Windows.   http://espeak.sourceforge.net.

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

To test:
$ espeak hello




Play mp3 on Raspberry Pi

To play mp3 on Raspberry Pi, using omxplayer command:

example:
$ omxplayer HelloWorld.mp3


scp, easiest way to copy file from Linux PC to Raspberry Pi

Example:

$ scp HelloWorld.mp3 pi@192.168.1.105:~/


Friday, September 5, 2014

Java on Raspberry Pi example: read Yahoo Weather, send to Arduino Uno, display on LCD Module

It's a Java example running on Raspberry Pi, read Yahoo Weather, then send to Arduino and display on 2x16 LCD Module.


Here, jSSC (Java Simple Serial Connector) is needed, refer to the post "Java serial communication with Arduino Uno with jSSC, on Raspberry Pi" to know how to add it to Netbeans project.

For sketch on Arduino Uno, read from serial port and write to 2x16 LCD Module, and connection of LCD Module, refer to the post in my another Arduino blog.

Apache HttpComponents is also needed to read Yahoo Weather with HttpClient, read previous post "Download and add Apache HttpComponents jar to Netbeans Project".

Java code:
package java_jssc_uno;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import jssc.SerialPort;
import jssc.SerialPortException;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class Java_jSSC_Uno {

    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("/dev/ttyACM0");
        try {
            System.out.println("Port opened: " + serialPort.openPort());

            try {
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
            }

            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Java_jSSC_Uno".getBytes()));
            //System.out.println("Port closed: " + serialPort.closePort());
        } catch (SerialPortException ex) {
            System.out.println(ex);
        }

        YahooWeather yahooWeather = new YahooWeather();
        yahooWeather.queryWeather();
        
        MyWeather myYahooWeatherResult = yahooWeather.getWeatherResult();
        System.out.println(myYahooWeatherResult.toString());
        
        try {
            serialPort.writeBytes(myYahooWeatherResult.description.getBytes());
            delay1s();
            
            serialPort.writeBytes(myYahooWeatherResult.city.getBytes());
            delay1s();
            serialPort.writeBytes(myYahooWeatherResult.region.getBytes());
            delay1s();
            serialPort.writeBytes(myYahooWeatherResult.country.getBytes());
            delay1s();
            
            serialPort.writeBytes(myYahooWeatherResult.conditiondate.getBytes());
            delay1s();

            serialPort.writeBytes(("humidity: " + myYahooWeatherResult.humidity).getBytes());
            delay1s();
            serialPort.writeBytes(("visibility: " + myYahooWeatherResult.visibility).getBytes());
            delay1s();
            serialPort.writeBytes(("pressure: " + myYahooWeatherResult.pressure).getBytes());
            delay1s();
            serialPort.writeBytes(("rising: " + myYahooWeatherResult.rising).getBytes());
            delay1s();
            
            serialPort.writeBytes(("chill: " + myYahooWeatherResult.windChill).getBytes());
            delay1s();
            serialPort.writeBytes(("direction: " + myYahooWeatherResult.windDirection).getBytes());
            delay1s();
            serialPort.writeBytes(("speed: " + myYahooWeatherResult.windSpeed).getBytes());
            delay1s();
            
            serialPort.writeBytes(("Sunrise: " + myYahooWeatherResult.sunrise).getBytes());
            delay1s();
            serialPort.writeBytes(("Sunset: " + myYahooWeatherResult.sunset).getBytes());
            delay1s();
            
            serialPort.writeBytes(myYahooWeatherResult.conditiontext.getBytes());
            delay1s();
        } catch (SerialPortException ex) {
            Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        try {
            System.out.println("Port closed: " + serialPort.closePort());
        } catch (SerialPortException ex) {
            Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    static private void delay1s(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

class MyWeather{
    String description;
    String city;
    String region;
    String country;
    
    String windChill;
    String windDirection;
    String windSpeed;
    
    String humidity;
    String visibility;
    String pressure;
    String rising;
    
    String sunrise;
    String sunset;
    
    String conditiontext;
    String conditiondate;
    
    @Override
    public String toString(){
        
        return "\n- " + description + " -\n\n" 
            + "city: " + city + "\n"
            + "region: " + region + "\n"
            + "country: " + country + "\n\n"

            + "Wind\n"
            + "chill: " + windChill + "\n"
            + "direction: " + windDirection + "\n"
            + "speed: " + windSpeed + "\n\n"
            
            + "humidity: " + humidity + "\n"
            + "visibility: " + visibility + "\n"
            + "pressure: " + pressure + "\n"
            + "rising: " + rising + "\n\n"
            
            + "Sunrise: " + sunrise + "\n"
            + "Sunset: " + sunset + "\n\n"
            
            + "Condition: " + conditiontext + "\n"
            + conditiondate +"\n";
    }
}

class YahooWeather {
    
    MyWeather weatherResult;
    
    public void queryWeather(){
        String weatherString = query();
        Document weatherDoc = convertStringToDocument(weatherString);
        
        weatherResult = parseWeather(weatherDoc);
    }

    private String query() {
        String qResult = "";
        //Yahoo Weather Query URL for New York
        String queryString = "http://weather.yahooapis.com/forecastrss?w=2459115";

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(queryString);

        try {
            HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Reader in = new InputStreamReader(inputStream);
                BufferedReader bufferedreader = new BufferedReader(in);
                StringBuilder stringBuilder = new StringBuilder();

                String stringReadLine;

                while ((stringReadLine = bufferedreader.readLine()) != null) {
                    stringBuilder.append(stringReadLine).append("\n");
                }

                qResult = stringBuilder.toString();

            }

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

        return qResult;
    }

    private Document convertStringToDocument(String src) {
        Document doc = null;

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser;

        try {
            parser = dbFactory.newDocumentBuilder();
            doc = parser.parse(new ByteArrayInputStream(src.getBytes()));
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(YahooWeather.class.getName()).log(Level.SEVERE, null, ex);
        }

        return doc;
    }

    private MyWeather parseWeather(Document srcDoc){
        
        MyWeather myWeather = new MyWeather();

        //<description>Yahoo! Weather for New York, NY</description>
        myWeather.description = srcDoc.getElementsByTagName("description")
            .item(0)
            .getTextContent();

        //<yweather:location city="New York" region="NY" country="United States"/>
        Node locationNode = srcDoc.getElementsByTagName("yweather:location").item(0);
        myWeather.city = locationNode.getAttributes()
            .getNamedItem("city")
            .getNodeValue();
        
        myWeather.region = locationNode.getAttributes()
            .getNamedItem("region")
            .getNodeValue();
        
        myWeather.country = locationNode.getAttributes()
            .getNamedItem("country")
            .getNodeValue();

        //<yweather:wind chill="60" direction="0" speed="0"/>
        Node windNode = srcDoc.getElementsByTagName("yweather:wind").item(0);
        myWeather.windChill = windNode.getAttributes()
            .getNamedItem("chill")
            .getNodeValue();
        
        myWeather.windDirection = windNode.getAttributes()
            .getNamedItem("direction")
            .getNodeValue();
        
        myWeather.windSpeed = windNode.getAttributes()
            .getNamedItem("speed")
            .getNodeValue();
        
        //<yweather:atmosphere humidity="82" visibility="6" pressure="30.2" rising="0"/>
        Node atmosphereNode = srcDoc.getElementsByTagName("yweather:atmosphere").item(0);
        myWeather.humidity = atmosphereNode.getAttributes()
            .getNamedItem("humidity")
            .getNodeValue();
        
        myWeather.visibility = atmosphereNode.getAttributes()
            .getNamedItem("visibility")
            .getNodeValue();
        
        myWeather.pressure = atmosphereNode.getAttributes()
            .getNamedItem("pressure")
            .getNodeValue();
        
        myWeather.rising = atmosphereNode.getAttributes()
            .getNamedItem("rising")
            .getNodeValue();

        //<yweather:astronomy sunrise="6:52 am" sunset="7:10 pm"/>
        Node astronomyNode = srcDoc.getElementsByTagName("yweather:astronomy").item(0);
        myWeather.sunrise = astronomyNode.getAttributes()
            .getNamedItem("sunrise")
            .getNodeValue();
        
        myWeather.sunset = astronomyNode.getAttributes()
            .getNamedItem("sunset")
            .getNodeValue();

        //<yweather:condition text="Fair" code="33" temp="60" date="Fri, 23 Mar 2012 8:49 pm EDT"/>
        Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
        myWeather.conditiontext = conditionNode.getAttributes()
            .getNamedItem("text")
            .getNodeValue();
        
        myWeather.conditiondate = conditionNode.getAttributes()
            .getNamedItem("date")
            .getNodeValue();

        return myWeather;
    }
    
    public MyWeather getWeatherResult(){
        return weatherResult;
    }
    
    @Override
    public String toString(){
        return weatherResult.toString();
    }
}


Download HERE.

- To know how to deploy to Raspberry Pi remotely with Netbeans 8, refer to the post "Set up Java SE 8 Remote Platform on Netbeans 8 for Raspberry Pi".

Remark:
This example port from my old exercise on Android, "Get weather info from Yahoo! Weather RSS Feed".


Download and add Apache HttpComponents jar to Netbeans Project

In the coming post, I have to use Apache HttpComponents jar in my code. The Apache HttpComponents™ project is responsible for creating and maintaining a toolset of low level Java components focused on HTTP and associated protocols.

It can be download here: http://hc.apache.org/.

This video show how to download and add the Apache HttpComponents jar to your project in Netbeans.

Thursday, September 4, 2014

Epiphany browser for Raspberry Pi released

Epiphany released, it is a improved web browser for Raspberry Pi. To install on Raspberry Pi, enter the command in Terminal:

$ sudo apt-get update
$ sudo apt-get dist-upgrade
$ sudo apt-get install epiphany-browser



Source:
http://www.raspberrypi.org/web-browser-released/

Wednesday, September 3, 2014

Java serial communication with Arduino Uno with jSSC, on Raspberry Pi

jSSC (Java Simple Serial Connector) - library for working with serial ports from Java. jSSC support Win32(Win98-Win8), Win64, Linux(x86, x86-64, ARM), Solaris(x86, x86-64), Mac OS X 10.5 and higher(x86, x86-64, PPC, PPC64).

This post show a Java program run on Raspberry Pi, using jSSC library, to send message to USB connected Arduino Uno board.


The development platform is a PC running Ubuntu with Netbeans 8, and deploy the program to Raspberry Pi remotely.

- To add jSSC library to our Netbeans Java project, read the post "Install and test java-simple-serial-connector with Arduino".

- The program code is almost same as the code on the page. With 3 seconds delay after serialPort.openPort(), to wait Automatic (Software) Reset on Arduino Uno board.
package java_jssc_uno;

import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.SerialPort;
import jssc.SerialPortException;

public class Java_jSSC_Uno {

    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("/dev/ttyACM0");
        try {
            System.out.println("Port opened: " + serialPort.openPort());

            try {
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Java_jSSC_Uno".getBytes()));
            System.out.println("Port closed: " + serialPort.closePort());
        }
        catch (SerialPortException ex){
            System.out.println(ex);
        }
    }
    
}

- To deploy to Raspberry Pi remotely with Netbeans 8, refer to the post "Set up Java SE 8 Remote Platform on Netbeans 8 for Raspberry Pi".


For the sketch (and extra info) on Arduino Uno, read the post in my Arduino blog.


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

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


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

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

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

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

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

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

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

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

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

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

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


Tuesday, September 2, 2014

Web base, remotely visual programming Raspberry Pi/Galileo with Wyliodrin

You can program your embedded devices using a browser on any computer.

Here is a short tutorial on how to program the Raspberry Pi with the new visual interface from Wyliodrin.


https://www.wyliodrin.com/