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".


No comments: