Tuesday Dec 24, 2013

Internet of Things (IoT) Christmas Special: Santa Detector (Part 5)

Well, this wraps up the Internet of Things (IoT) Christmas Special! Hope you enjoyed seeing the steps for creating the Java SE Embedded enabled Santa Detector!

The last step is to place the Raspberry Pi device connected to your Parallax PIR motion sensor nearby a plate of cookies and a glass of milk tonight. Then, start your Java SE Embedded SantaDetector.java app on the RPi before you go to bed, and tomorrow morning you and your child should see a tweet around midnight that shows that Santa came by.

(NOTE to parents [VERY IMPORTANT]: Remember to, you know, do the "thing" with the "thing" at around *mumble-mumble*. Got it? Nudge-nudge, wink-wink...) ;-)

Here's the full compilable Java source code again for reference:
https://java.net/projects/orbit/downloads/download/SantaDetector.java

That's a wrap!

Have a very Merry Christmas and a Happy Internet of Things (IoT) New Year! ;-)

See the full series of steps:
Internet of Things (IoT) Christmas Special: Santa Detector (Part 1)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 2)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 3)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 4)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 5)
<<< Previous  | Next >>>

Monday Dec 23, 2013

Internet of Things (IoT) Christmas Special: Santa Detector (Part 4)

So, let's take a closer look at the Java SE Embedded code snippet that will send out a tweet when the Santa Detector Raspberry Pi motion sensor is triggered, which will let the Oracle cloud and the Twitterverse know when Santa has arrived at your house. And, if you are doing this project with your child, it will prove once and for all that yes, there is a Santa Claus. Yay!

Here's the full compilable Java source code again for reference:
https://java.net/projects/orbit/downloads/download/SantaDetector.java

0. First, you need to have a Twitter 
account and you need to create your 
own Santa Detector Twitter app to 
make this work.  

Just follow the steps here:
Create Santa Detector Twitter App

And, make sure to do the following extra steps to make your Twitter app "Read and Write" enabled:

 1. Go to your Twitter app account by signing
  in with our Twitter login info:
    https://dev.twitter.com/
 2. Select your account icon -> My Applications
 3. Select the Santa Detector app (To create the
  app: see above)
 4. Click on the Settings tab
 5. In the section "Application Type Access:",
  select "Read and Write"
 6. Check the box for "Allow this application 
  to be used to Sign in with Twitter"
 7. Click "Update this Twitter's app settings"
 8. Click on the Details tab
 9. Refresh your Web browser
10. Make sure the Access level says: 
  "Read and write"
11. Copy the Twitter app information from the
  page into the SantaDetector.java code (Java
  variables near the top of the file):
   OAuth setting: Consumer Key
   OAuth setting: Consumer Secret
   Access token: Access token
   Access token: Access token secret

Next, take a look at the code snippet in the SantaDetector.java file that will send the tweet by calling the Java method tweetStatus():

 static 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(requestURI);

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

            if (tweetFlag) {
                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();
            }
            
            System.out.println("Tweet status = " + statusStr +
                    "\n basestring = " + basestring);

        } catch (IOException | NoSuchAlgorithmException |
                InvalidKeyException | IllegalStateException e) {
            e.printStackTrace();
        }
    }

You see that you can take the above code snippet and just make a tweetStatus library out of it. It is self contained as long as you add the following utilities that need to go along with it.

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


So, that's all there is to it to enable your Santa Detector to tweet when Santa has arrived. In the next blog post, we'll wrap it all up and figure out where to place the Raspberry Pi with the sensor for best coverage...

It's almost Christmas Eve, so get ready! ;-)

See the full series of steps:
Internet of Things (IoT) Christmas Special: Santa Detector (Part 1)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 2)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 3)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 4)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 5)
<<< Previous  | Next >>>

Sunday Dec 22, 2013

Internet of Things (IoT) Christmas Special: Santa Detector (Part 3)

Admiral Ackbar Santa thinks our Santa Detector is a trap. Well, he's right! We are setting up our Internet of Things (IoT) Santa Detector to catch Santa in the act on Christmas Eve to tell the world whether Santa Claus exists.

(I have a sneaky suspicion that we will detect Santa Claus on Christmas Eve and prove his existence. But, that's just a hunch... ;-) )

Admiral Ackbar Santa really shouldn't worry. We're not really going to try to trap Santa, just tweet when he's detected by our Java SE Embedded application.

So, you've followed the directions, so far, now you just need the Java source code for the Java SE Embedded app to run on your Raspberry Pi connected with a Parallax PIR sensor.

Here's the full Java source code that you'll need:
https://java.net/projects/orbit/downloads/download/SantaDetector.java

Here's a code excerpt from the full file above of Java SE Embedded code that uses the GPIO port on your Raspberry Pi connected to the Parallax PIR sensor to read in a value to detect if Santa is standing in front of the strategically located bait, er, um... I mean, plate of cookies and glass of milk:

//
// 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("Activating GPIO port: "
		       + 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 dir control of port
    FileWriter directionFile
	= new FileWriter("/sys/class/gpio/gpio"
			 + gpioChannel + "/direction");

    // Set port for input
    directionFile.write(GPIO_IN);
}
                
// Open RandomAccessFile handle for each GPIO port
for (int channum=0; channum < raf.length; channum++) {
    raf[channum] = new RandomAccessFile("/sys/class/gpio/gpio"
					+ GpioChannels[channum] + 
					"/value", "r");
}

//...


// Loop to keep reading sensor value
while (true) {
    int available;
            
	// Use RandomAccessFile handle to read in GPIO port value
	for (int channum=0; channum < raf.length; channum++) {
            
	    try {
		// Reset file seek pointer to read latest value 
		//   of GPIO port
		raf[channum].seek(0);
		raf[channum].read(inBytes);
	    } catch (IOException ioe) {
		ioe.printStackTrace();
	    }
                        
	    inLine = new String(inBytes);
            
	    // Check if "on" value was read
	    if (inLine.equals("1")) {

		// Specially mark value non-zero value
		gpioPortVal = 1;
		  
	    } else {
		// Else, no "on" value read
		gpioPortVal = 0;
	    }

	    System.out.println("Reading GPIO Port: " + 
			       GpioChannels[channum] +
			       "  Time: "+ timedateString + "  GPIO value = " + 
			       gpioPortVal);
	}
    }

So, as you can see in the code snippet above, the Java source code just keeps reading from the GPIO port where the PIR sensor is connected, whether it has a value of "0" (no motion detected) or "1" (motion detected), and that will tell us if Santa is there in front of the plate of cookies and glass of milk.

In the next blog post, we'll look at the Java code that will send out a Tweet when that happens, letting the cloud know when Santa has arrived at our location.

So, don't worry Admiral Ackbar Santa, it's all good! ;-)

See the full series of steps:
Internet of Things (IoT) Christmas Special: Santa Detector (Part 1)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 2)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 3)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 4)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 5)
<<< Previous  | Next >>>

Friday Dec 20, 2013

Internet of Things (IoT) Christmas Special: Santa Detector (Part 2)

Now, that you have all your parts, you should have this important part which is the motion sensor itself. It detects infrared motion and will light an internal LED and send a signal to the Java SE Embedded app when something (or someone like Santa Claus) passes in front of it.

The Raspberry Pi has enough power to also power this sensor, so you will next need to connect this part to your Raspberry Pi.

Just look at the next photo how it's done.

Flip the sensor over so that you can see the bottom of the circuit board where the labels are.

See: GPIO pin layout

Connect the left connector (OUT) to Pin #26 (GPIO07) on your Raspberry Pi GPIO bus. Connect the middle connector (VCC) to Pin #2 (+5 volts). And, connect the right connector (GND) to Pin #6 (GND) on your RPi.

And, that's it for the hardware part. Not too bad.

Next up we'll write a Java SE Embedded app to test the motion sensor. Santa won't have a chance this year... :-)

See the full series of steps:
Internet of Things (IoT) Christmas Special: Santa Detector (Part 1)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 2)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 3)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 4)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 5)
<<< Previous  | Next >>>

Thursday Dec 19, 2013

Internet of Things (IoT) Christmas Special: Santa Detector (Part 1)

Ho ho ho! It's time for an Internet of Things (IoT) Christmas Special project for Java SE Embedded on your Raspberry Pi. This one you can do with your kid. It's a Santa Detector, which was inspired by John Murphy's Arduino project.

This project will take a Parallax Passive Infra-Red sensor connected to your Raspberry Pi and a Java SE Embedded application code to send a Tweet when Santa has arrived at your house.

With this IoT Christmas Special project, there's going to be no way for Santa to sneak past your child this year. Heh, heh, heh... (or, should I say, "Ho, ho, ho"?) ;-)

Here is the parts list:

 1 Parallax PIR Sensor (Fry's #6726705)
 1 Raspberry Pi
 1 Milk and Cookies (for concealment)

So, go out and buy the parts above and come back here for the rest of the steps... "You better watch out, la-la-lala-laaa..."

See the full series of steps:
Internet of Things (IoT) Christmas Special: Santa Detector (Part 1)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 2)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 3)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 4)
Internet of Things (IoT) Christmas Special: Santa Detector (Part 5)
<<< Previous  | Next >>>

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!

About

Hinkmond Wong's blog on making the Internet of Things (IoT) smarter with Java Technologies

Search

Archives
« December 2013 »
SunMonTueWedThuFriSat
1
3
4
6
7
8
9
10
11
12
13
14
15
16
17
21
25
26
27
28
29
30
31
    
       
Today