Wednesday Dec 18, 2013

Why develop with Java SE Embedded on Raspberry Pi?

Why would you want to develop using Java SE Embedded technology on your Raspberry Pi? Why? Well, that question is like, "Why would you want to breathe in air?" It's just natural, of course.

But, if you're not convinced, check out this great article by Simon Ritter that appeared as a recent Electronic Design article.

See:

Java and RPi


Here's a quote:

 There are numerous reasons that make
 Java an attractive platform for 
 developing embedded type applications 
 using the Raspberry Pi:

 The very comprehensive set of included 
 class libraries. Java SE 7 has almost 
 4000 class libraries covering everything 
 from data structures to concurrency to 
 networking. This saves a lot of time by 
 not having to keep re-inventing the 
 wheel.
And, the big reason is that you'll want to use Java SE Embedded on your Raspberry Pi to follow along with my upcoming Internet of Things (IoT) Christmas Special. Now that's the best reason! ;-)

Thursday Dec 05, 2013

Happy Internet of Things (IoT) Hanukkah from Java SE Embedded!

Hope everyone has a happy Internet of Things (IoT) Hanukkah from Java SE Embedded and this Rasberry Pi running a Java SE Embedded app to light up the 8th night menorah light.

Here's the holiday Java code for your Internet of Things (IoT) menorah:

/*
 * Java Embedded Raspberry Pi GPIO app
 */

import java.io.FileWriter;
import java.io.File;

/**
 *
 * @author hinkmond
 */
public class JavaEmbMenorah {
    
    static final String GPIO_OUT = "out";
    static final String GPIO_ON = "1";
    static final String GPIO_OFF = "0";
    
    static String[] GpioChannels = 
    { "0", "1", "4", "17", "21", "22", "10", "9", "11" };

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        FileWriter[] commandChannels;
        
        try {
            
            /*** Init GPIO port for output ***/
            
            // Open file handles to GPIO port unexport and export controls
            FileWriter unexportFile = 
                    new FileWriter("/sys/class/gpio/unexport");
            FileWriter exportFile = 
                    new FileWriter("/sys/class/gpio/export");

            for (String gpioChannel : GpioChannels) {
                System.out.println(gpioChannel);
    
                // Reset the port
                File exportFileCheck = new File("/sys/class/gpio/gpio"+gpioChannel);
                if (exportFileCheck.exists()) {
                    unexportFile.write(gpioChannel);
                    unexportFile.flush();
                }
            
                // Set the port for use
                exportFile.write(gpioChannel);   
                exportFile.flush();

                // Open file handle to port input/output control
                FileWriter directionFile =
                    new FileWriter("/sys/class/gpio/gpio" + gpioChannel + 
                        "/direction");
            
                // Set port for output
                directionFile.write(GPIO_OUT);
                directionFile.flush();
            }
            
            /*** Send commands to GPIO port ***/
            
            commandChannels = new FileWriter[GpioChannels.length];
            
            for (int channum=0; channum < GpioChannels.length; channum++) {
                
                // Open file handle to issue commands to GPIO port
                commandChannels[channum] = 
                        new FileWriter("/sys/class/gpio/gpio" +
                        GpioChannels[channum] + "/value");
            }
            
            int channum = 0;
            int sleepPeriod = 1000; // (1 sec. in milliseconds)
            // Loop forever
            while (true) {
                
                if (++channum >= GpioChannels.length) {
                    channum = 0;
                }
                
                // Refresh Menorah Lights
                commandChannels[channum].write(GPIO_ON);
                commandChannels[channum].flush();
               
                
                // Wait for a while
                java.lang.Thread.sleep(sleepPeriod);
        
            }

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

Monday Dec 02, 2013

Java Embedded Holiday Gift Idea: Choose PS4 with Java ME CDC, not Xbox One

Here's a holiday gift idea for the 2013 shopping season: When shopping for one of those new generation fancy-schmancy video game consoles, make sure to choose the Sony PS4, which has the Java ME CDC platform built into the PS4 Blu-ray player. The Java ME CDC platform (which the Java ME CDC team and I helped work on at Sun Microsystems, Inc. and now at Oracle) ships on many devices found on store shelves today, such as the PS4.

So, for commercially shipping (and profitable) Java products (such as Java ME CDC) on the PS4, make sure to pick the gift that comes with Java technology for your friends and family. Plus, the PS4 is a kick-b*tt console compared to the Xbox One, so you can't go wrong. ;-)

Happy Java Technology-Enabled Cyber Monday!

Wednesday Nov 27, 2013

Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 6)

So, that's a wrap everyone. Hope you enjoyed the Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter!

Leave me feedback on this project in the blog comments (open for 1 week), if you used it for your holiday bird, or if you just followed along and had fun reading. It's good to hear if you ran into any problems or have any questions about using Java SE Embedded for your own Internet of Things project. (Tech support [me] will be open for a few hours tomorrow if you have issues, but response time will vary according to which football game is on) :-)

So remember: Java technology is a great way to rapidly develop your own IoT applications.

Also, send links to your Twitter accounts if you get them working from your Raspberry Pi. I'll be sure to follow your Twitter feed of your own Java SE Embedded IoT device, and be sure to follow mine at: https://twitter.com/iottweet

A very Happy Thanksgiving (and Happy Hanukkah) to all!

Here are the full steps to this project:
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 1)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 2)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 3)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 4)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 5)

Happy Turkey Tweeting!

Monday Nov 25, 2013

Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 4)

Now, on to the next step which is to write the Java SE Embedded code to automatically send an Internet of Things (IoT) tweet from your Raspberry Pi attached to your cooking turkey to a Twitter account. For this part you'll need to create your own Twitter app for your IoT Turkey, which is easy to do. Just follow the steps: here

After you are done with the above steps to create your own Twitter app, make note of the following settings from your Twitter app:

 1. OAuth setting: Consumer Key
 2. OAuth setting: Consumer Secret
 3. Access token: Access token
 4. Access token: Access token secret

You will use your Twitter app values from above in your Java Embedded program. Just replace the above values into the following Java Embedded code:

    // Application Defined Settings
    static String consumerKey = "XXXXXXXXXXXXXXXXXXXXXX";
    static String consumerSecret = 
            "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    static String accessToken = 
            "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    static String accessTokenSecret = 
            "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; 
    
    static String requestURI = "https://api.twitter.com/1.1/statuses/update.json";

Next, here is the code to send the tweet:

    void tweetStatus(String statusStr) {

        boolean verboseFlag = true;
        String requestURIEnc = null;
        
        try {
            requestURIEnc = URLEncoder.encode(requestURI, "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            uee.printStackTrace();
        }
        
        try {

            if (statusStr == null) {
              statusStr = "Tweet, tweet.  Hello world!";
            }

            // Construct encoded string, parameter encoded string, & data
            String statusEncStr = URLEncoder.encode(statusStr, "UTF-8");

            // Param encode status string twice: once for unsafe characters 
            //  String, once for escaping % for Signature base string
            String statusUnsafeEncStr = unsafeEncode(unsafeEncode(statusStr));

            String postData = "status="+statusEncStr;

            // First set the default cookie manager
            CookieHandler.setDefault(new CookieManager(null,
                    CookiePolicy.ACCEPT_ALL));

            // Send postData
            URL url = new URL("https://api.twitter.com/1.1/statuses/update.json");

            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");

            // Get current date time with Calendar()
            Calendar cal = Calendar.getInstance();
            String timeStr = String.
                    valueOf(cal.getTimeInMillis()).substring(0, 10);

            String basestring = "POST&" + requestURIEnc + 
                    "&oauth_consumer_key%3D" + consumerKey + 
                    "%26oauth_nonce%3D5bffa3b2711bbcdaa4f301" + timeStr + 
                    "%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D" 
                    + timeStr + "%26oauth_token%3D" + accessToken + 
                    "%26oauth_version%3D1.0" + "%26status%3D" + 
                    statusUnsafeEncStr;

            String secretsStr = consumerSecret+"&"+accessTokenSecret;
            SecretKeySpec keySpec = 
                    new SecretKeySpec(secretsStr.getBytes(),
                    "HmacSHA1");

            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(keySpec);
            byte[] result = mac.doFinal(basestring.getBytes());

            String signature = URLEncoder.encode(base64Encode(result), "UTF-8");

            String credentials = 
                    "oauth_consumer_key=\"" + consumerKey + "\"," +
                    "oauth_nonce=\"5bffa3b2711bbcdaa4f301" + timeStr + 
                    "\"," +
                    "oauth_signature=\"" + signature + "\"," +
                    "oauth_signature_method=\"HMAC-SHA1\"," +
                    "oauth_timestamp=\"" + timeStr + "\"," +
                    "oauth_token=\"" +
                    accessToken + "\"," +
                    "oauth_version=\"1.0\"";

            conn.addRequestProperty("Authorization", "OAuth " + credentials);

            String lenStr = String.valueOf(postData.length());
            conn.setRequestProperty("Content-Length", lenStr);
            conn.setRequestProperty("Content-Type", 
                    "application/x-www-form-urlencoded");

            // Do as if you're using Firefox 3.6.3
            conn.setRequestProperty("User-Agent", 
                    "Mozilla/5.0 (Windows; U; Windows NT 5.1; "+
                    "en-US; rv:1.9.2.3) Gecko/20100401"); 

            conn.connect();
            OutputStream output = conn.getOutputStream();

            output.write(postData.getBytes("UTF-8"));

            // Get the response
            InputStream response = conn.getInputStream();
            BufferedReader rd =
                    new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = rd.readLine()) != null) {
                if (verboseFlag) {
                    System.out.println(line);
                }
            }
            rd.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

And, here's some code for the supporting utility methods:

   public static String unsafeEncode(String input) {
        StringBuilder resultStr = new StringBuilder();
        for (char ch : input.toCharArray()) {
            if (isUnsafe(ch)) {
                resultStr.append('%');
                resultStr.append(toHex(ch / 16));
                resultStr.append(toHex(ch % 16));
            } else {
                resultStr.append(ch);
            }
        }
        return resultStr.toString();
    }

    private static char toHex(int ch) {
        return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
    }

    private static boolean isUnsafe(char ch) {
        if (ch > 128 || ch < 0) {
            return true;
        }
        return "$&+,/:;=?@ \"<>#%{}|\\^~[]`'!_*".indexOf(ch) >= 0;
    }
    
    
    private final static char[] BASE64CHARS = 
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            .toCharArray();

    private static int[]  intChars   = new int[128];
    
     /**
     * Translates the specified byte array into Base64 string.
     *
     * @param inputBuffer byte array (not null)
     * @return the translated Base64 string (not null)
     */
    public static String base64Encode(byte[] inputBuffer){
        
        // Check if intChars array needs to be init'd
        if (intChars.length == 0) {
            for(int index=0; index < BASE64CHARS.length; index++){
                intChars[BASE64CHARS[index]]= index;
            }
        }
        
        int bufferSize = inputBuffer.length;
        char[] charArray = new char[((bufferSize + 2) / 3) * 4];
        int charIndex = 0;
        int inputIndex = 0;
        while(inputIndex < bufferSize){
            byte byte0 = inputBuffer[inputIndex++];
            byte byte1 = (inputIndex < bufferSize) ? 
                    inputBuffer[inputIndex++] : 0;
            byte byte2 = (inputIndex < bufferSize) ? 
                    inputBuffer[inputIndex++] : 0;

            int mask = 0x3F;
            charArray[charIndex++] = BASE64CHARS[(byte0 >> 2) & mask];
            charArray[charIndex++] = BASE64CHARS[((byte0 << 4) | 
                    ((byte1 & 0xFF) >> 4)) & mask];
            charArray[charIndex++] = BASE64CHARS[((byte1 << 2) | 
                    ((byte2 & 0xFF) >> 6)) & mask];
            charArray[charIndex++] = BASE64CHARS[byte2 & mask];
        }
        
        switch(bufferSize % 3){
            case 1: charArray[--charIndex]  = '=';
            case 2: charArray[--charIndex]  = '=';
        }
        
        return new String(charArray);
    }

That's all you need to send tweets to your Twitter app using Java SE Embedded. Easy-peazy! Next, we'll put it all together, so that your Raspberry Pi takes the Vernier Go!Temp temperature readings from your roasting bird, and sends out tweet updates, plus a tweet to tell the Twitterverse when your turkey is done. That's something delicious! :-)

See the full series on the steps to this cool demo:
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 1)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 2)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 3)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 4)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 5)

Thursday Nov 21, 2013

Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 3)

OK, sports fans. You've got your Vernier Go!Temp USB probe connected. It looks good with lsusb and you can see the /dev/ldusb0 device in your Raspberry Pi Linux shell.

So, how do you write a Java SE Embedded app to read in the turkey temp values. Well, as with most things, you search the Web and you can find how it was done previously in other non-Java inferior programming languages. ;-) Here's a great example in Python on the finninday.net site.

See: finniday.net Go!Teamp example in Python

It shows the reverse engineered byte format of the data coming over USB from the Vernier Go!Temp probe. Booyah! That's what we need to write a Java SE Embedded app. And, here it is...

/**
 *
 * @author hinkmond
 * Copyright © 2013 Oracle and/or its affiliates. All rights reserved.
 */
public class TurkeyTweeter {

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        Date date;
        FileInputStream fis = null;
        DataInputStream dis = null;
        byte   b[];
        
        double tempavg, c, f;
        int    samplecount=0, sequence=0, temp1=0, temp2=0, temp3=0;
        
        final double VERNIER_SCALING_FACTOR=126.74;
        final double VERNIER_CALIBRATION_OFFSET=5.4;

        b = new byte[8];

        // Loop to keep reading temperature
        while (true) {
            int available;

            try {
                fis = new FileInputStream("/dev/ldusb0");
                dis = new DataInputStream(fis);
            } catch (FileNotFoundException fnfe) {
                System.out.println("Cannot find temp sensor");
                fnfe.printStackTrace();
                System.exit(-1);
            }

            // Read 8 bytes from Vernier Go!Temp USB probe
            //   Format:
            //     Byte 0:   Sample Count
            //     Byte 1:   Sequence Index
            //     Byte 2-3: First temp sample
            //     Byte 4-5: Second temp sample
            //     Byte 6-7: Third temp sample
            try {
                if (dis != null) {
                    available = dis.read(b, 0, 8);
                    samplecount = b[0];
                    sequence = b[1];
                    temp1 = b[2] + b[3] * 256;
                    temp2 = b[4] + b[5] * 256;
                    temp3 = b[6] + b[7] * 256;
                }
            } catch (IOException ioe1) {
                System.out.println("Unable to get data from temp sensor");
                ioe1.printStackTrace();
            }
            
            tempavg = (temp1 + temp2 + temp3) / 3.0;
            c = tempavg / VERNIER_SCALING_FACTOR - VERNIER_CALIBRATION_OFFSET;
            
            // Convert from Fahrenheit to Celcius
            f = ((9.0/5.0) * c) + 32.0;
            
            double temperature = roundDouble(f);
            
            date = Calendar.getInstance().getTime();

            Format formatter = new SimpleDateFormat("E MMM d kk:mm:ss");
            String timedateString = formatter.format(date);

            System.out.println(timedateString+"  "+temperature);

            try {
                if (dis != null)
                    dis.close();
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }
    }

   public static double roundDouble(double value) {
        double result = value * 100;
        result = Math.round(result);
        result = result / 100;
        return(result);
   }
}

Compile using javac, lather, rinse, repeat. And, here's the output running on the RPi (NOTE: Remember, you must run as root to access the /dev/ldusb0 device):

pi@raspberrypi ~ $ sudo java -jar TurkeyTweeter.jar
Thu Nov 21 16:42:59  71.59
Thu Nov 21 16:43:00  72.39
Thu Nov 21 16:43:01  72.39
Thu Nov 21 16:43:02  72.39
Thu Nov 21 16:43:03  72.39
Thu Nov 21 16:43:04  72.39
Thu Nov 21 16:43:05  72.39
Thu Nov 21 16:43:06  72.39
Thu Nov 21 16:43:07  72.39
Thu Nov 21 16:43:08  72.39
Thu Nov 21 16:43:09  72.39
...
As you can see, it's 72 degrees Fahrenheit in my office. The turkey won't be that temperature roasting in the oven on Thanksgiving, but we have now confirmed this part of the Turkey Tweeter works. Exciting, isn't it? :-) Next up, we will write the Java code to tweet out the values of our poor turkey as it cooks... (Yeah, poor turkey until it's inside my tummy. Then, it's yummy turkey!)

See the full series on the steps to this cool demo:
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 1)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 2)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 3)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 4)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 5)

Monday Nov 18, 2013

Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 2)

By now you should have received your Vernier Go!Temp USB Temperature Probe and it is getting really close now to Turkey Day, so you want kick your Internet of Things (IoT) Turkey Tweeter project into high gear now.

First, we need to test the temperature probe before sticking it into unknown places, namely our delicious IoT bird on Thanksgiving. So, take your Go!Temp USB temperature probe and plug it into your Raspberry Pi device, just like in this photo.

See:

Connect Go!Temp Probe

If all went well on your Raspberry Pi, you should be able to bring up a terminal shell connected to your RPi and type "lsusb" to verify that the Go!Temp probe is now connected.

pi@raspberrypi ~ $ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp.
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.
Bus 001 Device 005: ID 08f7:0002 Vernier EasyTemp/Go!Temp

If your output looks like above, especially the last line where it says the Vernier Go!Temp was recognized and is connected as Device 005, you are golden.

One last check before we start to program using a Java SE Embedded app to grab the temperature readings is to make sure the /dev/ldusb0 device is present. So, type this command and make sure your output matches:

pi@raspberrypi ~ $ ls -l /dev/ldusb0
crw------T 1 root root 180, 176 Nov 18 17:25 /dev/ldusb0

If all that looks good, you're ready for the next step which is to write a Java SE Embedded app to read the temperature values, and eventually write code with IoT intelligence to tweet out the status of your turkey while it's cooking so that it becomes an Internet of Things connected bird on Twitter. Look for that in the next part of this series... Mmmmm... I can almost smell that turkey roasting... :-)

See the full series on the steps to this cool demo:
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 1)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 2)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 3)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 4)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 5)

Wednesday Nov 06, 2013

Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 1)

It's time for the Internet of Things (ioT) Thanksgiving Special. This time we are going to work on a special Do-It-Yourself project to create an Internet of Things temperature probe to connect your Turkey Day turkey to the Internet by writing a Thanksgiving Day Java Embedded app for your Raspberry Pi which will send out tweets as it cooks in your oven.

If you're vegetarian, don't worry, you can follow along and just run the simulation of the Turkey Tweeter, or better yet, try a tofu version of the Turkey Tweeter.

Here is the parts list:

 1 Vernier Go!Temp USB Temperature Probe
 1 Uncooked Turkey
 1 Raspberry Pi (not Pumpkin Pie)
 1 Roll thermal reflective tape
You can buy the Vernier Go!Temp USB Temperature Probe for $39 from here: http://www.vernier.com/products/sensors/temperature-sensors/go-temp/. And, you can get the thermal reflective tape from any auto parts store. (Don't tell them what you need it for. Say it's for rebuilding your V-8 engine in your Dodge Hemi. Avoids the need for a long explanation and sounds cooler...) ;-)

The uncooked turkey can be found in your neighborhood grocery store. But, if you're making a vegetarian Tofurkey, you're on your own... The Java Embedded app will be the same, though (Java is vegan). :-)

So, grab all your parts and come back here for the next part of this project...

See the full series on the steps to this cool demo:
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 1)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 2)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 3)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 4)
Internet of Things (IoT) Thanksgiving Special: Turkey Tweeter (Part 5)

Wednesday Oct 30, 2013

Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 5)

So, here's the finished product. I have 8 networked Raspberry Pi devices strategically placed around our Oracle Santa Clara Building 21 office. I attached a JFET transistor based EMF sensor on each device to capture any strange fluctuations in the electromagnetic field (which supposedly, paranormal spirits can change as they pass by).

And, I have have a Web app (embedded in this page) which can take the readings and show a graphical display in real-time. As you can see, all the Raspberry Pi devices are blinking away green, indicating they are all operational and all sensors are working correctly. But, I don't see anything... Darn...

Maybe, I have to stare at the Web app for a while. I don't know when the "alleged" ghosts in our Oracle Santa Clara office are supposed to be active, but let me know if you see anything...

Oh, and by the way, Happy Halloween from the Internet of Spooky Things!

See the previous posts for the full series on the steps to this cool demo:
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 1)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 2)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 3)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 4)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 5)

Monday Oct 28, 2013

ARM TechCON 2013 presentation: Java SE 8 Compact Profiles

I'll be giving a technical session presentation at ARM TechCON 2013 this Wed. 10/30 @ 11:30am. So if you are in Santa Clara, Calif. come over to the conference and hear me present on this fun-filled topic!

See:

Java SE 8 Compact Profiles

Here's a quote:

 Java SE 8 has a new Compact Profiles 
 feature that allows for three new
 specification–compliant subsets of 
 Java SE 8 APIs. Compact Profiles will 
 enable the creation of Java SE 8 
 runtimes that support configurations 
 that previously were possible only 
 with the CDC version of J2ME...
It's an important topic in today's mad, mad world of Embedded Development. You never want to develop in Java for small devices with your Compact Profiles. It's just not what you'd want! ;-)

Friday Oct 25, 2013

Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 4)

And now here's the Java code that you'll need to read your ghost sensor on your Raspberry Pi

The general idea is that you are using Java code to access the GPIO pin on your Raspberry Pi where the ghost sensor (JFET trasistor) detects minute changes in the electromagnetic field near the Raspberry Pi and will change the GPIO pin to high (+3 volts) when something is detected, otherwise there is no value (ground).

Here's that Java code:

try {
            
    /*** Init GPIO port(s) for input ***/
    
    // Open file handles to GPIO port unexport and export controls
    FileWriter unexportFile = 
            new FileWriter("/sys/class/gpio/unexport");
    FileWriter exportFile = 
            new FileWriter("/sys/class/gpio/export");
    for (String gpioChannel : GpioChannels) {
        System.out.println(gpioChannel);
             // Reset the port
        File exportFileCheck = new 
	    File("/sys/class/gpio/gpio"+gpioChannel);
        if (exportFileCheck.exists()) {
            unexportFile.write(gpioChannel);
            unexportFile.flush();
        }
    
        // Set the port for use
        exportFile.write(gpioChannel);   
        exportFile.flush();
         // Open file handle to input/output direction control of port
        FileWriter directionFile =
            new FileWriter("/sys/class/gpio/gpio" + gpioChannel + 
                "/direction");
    
        // Set port for input
        directionFile.write(GPIO_IN);
    }
    
    /*** Read data from each GPIO port ***/
    RandomAccessFile[] raf = new RandomAccessFile[GpioChannels.length];
    
    int sleepPeriod = 10;
    final int MAXBUF = 256;
    
    byte[] inBytes = new byte[MAXBUF]; 
    String inLine;
    
    int zeroCounter = 0;
    
    // Get current timestamp with Calendar()
    Calendar cal;
    DateFormat dateFormat = 
            new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
    String dateStr;
    
    // Open RandomAccessFile handle to each GPIO port
    for (int channum=0; channum < raf.length; channum++) {
        raf[channum] = new RandomAccessFile("/sys/class/gpio/gpio"
                + GpioChannels[channum] + "/value", "r");
    }
    
    // Loop forever
    while (true) {
        
        // Get current timestamp for latest event
        cal = Calendar.getInstance();
        dateStr = dateFormat.format(cal.getTime());

        // Use RandomAccessFile handle to read in GPIO port value
        for (int channum=0; channum < raf.length; channum++) {
            
            // Reset file seek pointer to read latest value of GPIO port
            raf[channum].seek(0);
            raf[channum].read(inBytes);
            inLine = new String(inBytes);
            
            // Check if any value was read
            if (inLine != null) {
                
                // Compress 0 values so we don't see too many 
                //   unimportant lines
                if (inLine.startsWith("0")) {
                    if (zeroCounter < 1000) {
                        zeroCounter++;
                    } else {
                        System.out.print(dateStr + ": " + inLine);
                        zeroCounter = 0;
                    }
                } else {
                    // Else, specially mark value non-zero value
                    System.out.print("***" + dateStr + ": " + inLine);
                    zeroCounter = 0;
                }
            }
             // Wait for a while
            java.lang.Thread.sleep(sleepPeriod);

        }
    }
} catch (Exception exception) {
   exception.printStackTrace();
}


And, then we just load up our Java SE Embedded app, place each Raspberry Pi with a ghost sensor attached in strategic locations around our Santa Clara office (which apparently is very haunted by ghosts from the Agnews Insane Asylum 1906 earthquake), and watch our analytics for any ghosts.

Easy peazy.

See the posts for the full series on the steps to this cool demo:
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 1)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 2)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 3)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 4)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 5)

Tuesday Oct 22, 2013

Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 3)

So, let's now connect the parts together to make a Java Embedded ghost sensor using a Raspberry Pi. Grab your JFET transistor, LED light, wires, and breadboard and follow the connections on this diagram.

The JFET transistor plugs into the breadboard with the flat part facing left. Then, plug in a wire to the same breadboard hole row as the top JFET lead (green in the diagram) and keep it unconnected to act as an antenna. Then, connect a wire (red) from the middle lead of the JFET transistor to Pin 1 on your RPi GPIO header. And, connect another wire (blue) from the lower lead of the JFET transistor to Pin 25 on your RPi GPIO header, then connect another (blue) wire from the lower lead of the JFET transistor to the long end of a common cathode LED, and finally connect the short end of the LED with a wire (black) to Pin 6 (ground) of the RPi GPIO header.

That's it. Easy.

Now test it. See:

Ghost Sensor Testing

Here's a video of me testing the Ghost Sensor circuit on my Raspberry Pi. We'll cover the Java SE app needed to record the ghost analytics in the next post.

See the posts for the full series on the steps to this cool demo:
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 1)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 2)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 3)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 4)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 5)

Monday Oct 21, 2013

Freescale One Box Unboxing (then installing Java SE Embedded technology)

So, I get a FedEx delivery the other day... "What cool device could be inside this FedEx Overnight Express Large Box?" I was wondering...


Could it be a new Linux/ARM target device board, faster than a Raspberry Pi and better than a BeagleBone Black???


Why, yes! Yes, it was a Linux/ARM target device board, faster than anything around!


It was a Freescale i.MX6 Sabre Smart Device Board (SDB)! Cool... Quad Core ARM Cortex A9 1GHz with 1GB of RAM. So, cool... I installed the Freescale One Box OpenWRT Linux image onto its SD card and booted it up into Linux.


But, wait! One thing was missing... What was it? What could be missing? Why, it had no Java SE Embedded installed on it yet, of course! So, I went to the JDK 7u45 download link. Clicked on "Accept License Agreement", and clicked on "jdk-7u45-linux-arm-vfp-sflt.tar.gz", installed the bad boy, and all was good. Java SE Embedded 7u45 on a Freescale One Box. Nice...

Wednesday Oct 16, 2013

Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 2)

To start out our ghost hunting here at the Oracle Santa Clara campus office, we first need a ghost sensor. It's pretty easy to build one, since all we need to do is to create a circuit that can detect small fluctuations in the electromagnetic field, just like the fluctuations that ghosts cause when they pass by... Naturally, right?

So, we build a static charge sensor and will use a Java Embedded app to monitor for changes in the sensor value, running analytics using Java technology on a Raspberry Pi. Bob's your uncle, and there you have it: a ghost sensor.

See:

Ghost Detector

So, go out to Radio Shack and buy up these items:

shopping list:

  1 - NTE312 JFET N-channel 
      transistor 
      (this is in place of 
       the MPF-102)
  1 - Set of Jumper Wires
  1 - LED
  1 - 300 ohm resistor
  1 - set of header pins
Then, grab a flashlight, your Raspberry Pi, and come back here for more instructions... Don't be afraid... Yet.

See the posts for the full series on the steps to this cool demo:
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 1)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 2)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 3)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 4)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 5)

Friday Oct 11, 2013

Halloween: Season for Internet of Spooky Things (IoST) and Java Embedded (Part 1)

It's Halloween time! And, you know what that means. Ghost stories... WooooOOOoooo... Not many people know this, but the Oracle office in Santa Clara, Calif. (formerly the Sun Microsystems, Santa Clara campus) where I happen to work, was built on the same site as the Agnews Insane Asylum which was orginally built in 1885.

Unfortunately, in 1906 the original Agnews Asylum suffered a fire during the San Francisco earthquake and became the site of Santa Clara Valley's "greatest loss of life" resulting from the quake. 117 patients and staff were killed and buried in mass graves on the site (same place as where I work now). The main building (seen in the photo) and some others were irreparably damaged. Ever since then, there have been strange reports of workers witnessing apparitions, hearing strange laughter and screaming, sensing cold spots and seeing freezer doors fly open violently and eject their contents (which is pretty darn scary, if you ever saw what's been left and forgotten in our breakroom refrigerators over time by co-workers).

Quite frankly, late some evenings, after a long day at work, I've smelled something strange burning in the air. Usually, it's someone who microwaved their popcorn too long in the breakroom. But, it could be ghosts...

See:

Agnews Insane Asylum

Here's a quote:

 Following this disaster, Agnews was 
 reconstructed in the so-called 
 Mediterranean Revival style, 
 resembling a college campus of 
 two-story buildings; it re-opened 
 circa 1911 as Agnews State Mental 
 Hospital.

That second mental hospital mentioned in the above quote lasted until Sun Microsystems demolished it and built an office complex on top of that, then Oracle acquired Sun Microsystems including the Santa Clara campus and here we are today.

So, what better way to celebrate Halloween than by building an Internet of Spooky Things (IoST) ghost sensor connected to a Raspberry Pi running Java Embedded to track ghosts in our office building. I'm going to show you how you can build this too for your Raspberry Pi then run a Java Embedded app to collect ghost analytics.

We'll see how many ghosts we can detect with our IoST gateway device here at the Oracle Santa Clara campus office by placing my embedded device and sensor in different locations throughout our office building in the next few weeks... WoooOOOooooo... Stay tuned...

See the series of posts for the steps to this cool demo:
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 1)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 2)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 3)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 4)
Halloween: Season for Java Embedded Internet of Spooky Things (IoST) (Part 5)

About

Hinkmond Wong's blog on making Machine to Machine (M2M) and the Incredible Internet of Things (IoT) smarter with Java Embedded Technologies

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
2
3
4
5
6
7
8
9
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today