Java Sun SPOT Application Development using Java ME (J2ME)

Home --> Notes --> Let your Java app "feel the rain" on its skin

Let your Java app "feel the rain" on its skin

Your journey begins with the task of gently introducing your Java applications to the realities of the physical world, an area that normally exists beyond the confines of the limited and rather myopic worldview of the typical Java midlet.

In this paradigm that is exemplified by the new Sun SPOTs, a midlet without a way to "feel the rain" on its skin, is like a gourmet diner who is finally allowed access to a connoiseur's nirvana, only to find out that he has a cold and cannot taste any of the offerings placed before him.

As one singer put it:

Feel the rain on your skin
No one else can feel it for you
Only you can let it in
No one else, no one else
Can speak the words on your lips
Drench yourself in words unspoken
Live your life with arms wide open
Today is where your book begins
The rest is still unwritten

- Natasha Bedingfield

You will help write this book, and your Java applications will finally be able to "feel" things that they could not have done otherwise.

As a first step, we'll allow our new midlet to sense temperature and light.

The first thing you need to do is to create a Midlet skeleton from the demo applications that are included in the Sun SPOT kit. It is ok to start from scratch if you want, but why struggle when someone else has already made the path for you easier? I used the BuiltInSensorsDemo demo application and closely studied the source of the BuiltInSensorsDemo class. A quick look at the short source code will immediately assuage any fears by mobile developers that the Midlets here are vastly different than those in mobile devices.

For example, the same life cycle templates are in there:

    protected void startApp() throws MIDletStateChangeException { 
        try {
            run();
        } catch (IOException ex) { //A problem in reading the sensors. 
            ex.printStackTrace();
        }
    }


    protected void pauseApp() { 
    }


    protected void destroyApp(boolean arg0) throws MIDletStateChangeException { 
    }

The one big difference of course if that this Midlet uses some quite unusual libraries.

import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.io.IScalarInput;
import com.sun.spot.sensorboard.io.ITemperatureInput;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.sensorboard.peripheral.ISwitch;
import com.sun.spot.sensorboard.peripheral.ILightSensor; 
import com.sun.spot.sensorboard.peripheral.LEDColor;
import com.sun.spot.util.Utils;
import java.io.IOException;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

The easiest way to get started is to simply copy that demo application folder, modify the contents and rename the folder, then open the lot using Netbeans. In this case, I simply copied the entire BuiltInSensorsDemo folder and renamed the new folder to "PickyMidlet". I then changed several things in the folder to reflect the new name and make sure it compiles and deploys correctly. In the project.xml file in the nbproject folder, rename the BuiltInSensorsDemo to PickyMidlet. I also changed the name in the build.xml file to reflect the change in nomenclature. FInally, in the resources/META-INF/manifest.mf file, change the name of the midlet to reflect the new name.

Now, open Netbeans 5.0 and go on over to where you have your "PickyMidlet" folder. Open the project and Netbeans will show the new project in the left hand pane.

Sun SPOT and Java ME/J2ME.

Now, safely rename the original midlet to the new PickyMidlet name via Netbeans' refactoring. You can obviously leave the same name, but just for the sake of differentiation it would probably be a good idea to change the name.

Sun SPOT and Java ME/J2ME.

Set PickyMidlet as the main project and then clean and build the project. You should be able to compile the project with no problems as this is based completely as of this point to the old demo Midlet.

The original midlet cleverly uses various LED lights to convey changes in movement, temperature, and light intensity to outside observers. However, I could do without the blinking lights and so I modified the original code to make it simpler for demonstration purposes. I also personalized the Midlet by having it respond to variations in temperature as a person might. As you can see from the code sample below, getting values from the sensor boards are easy and simple to do.

    private void run()throws IOException {  

        while(true) {
		    // determine the temperature
            int theTemperature = (int) (tempSensor.getCelsius());
	        System.out.println("Current temperature is "+theTemperature+" degrees.");		

			if (theTemperature < 15){
                   System.out.println ("It's too cold in here!");             
            }
			else if (theTemperature > 30) {
                   System.out.println ("It's too hot in here!");
			}	    
			else {
                   System.out.println ("Ahhh, that's just right!"); 
            }
			
            // determine the light level
            int lightLevel = lightSensor.getValue();        

            System.out.println ("Current light level is "+lightLevel);
            
            // send the info to external classes
            sendInfo (theTemperature,lightLevel);
            
            try {
                 Thread.sleep (60000);
            } catch (Exception e) {            
              }
		   
            Utils.sleep(200); 
        }
    }
	

 

Now, we can move the code to one of the Sun SPOT devices. Clean and build the entire project using Netbeans, connect one of the non-basestation Sun SPOT devices to your host computer using the USB cord, then DEPLOY by highlighting the project name on the left pane and selecting DEPLOY TO SUN SPOT.

Sun SPOT and Java ME/J2ME.

The IDE should give you an output very similar to the one below if you are successful.

init:
Using Sun SPOT device on port COM6
[loaded object memory from 'file://C:/Program Files/Sun/SunSPOT/sdk/lib/translator.suite']
[loaded object memory from 'file://C:/Program Files/Sun/SunSPOT/sdk/arm/transducerlib.suite']
[Loaded org.sunspotworld.demo.PickyMidlet]
[Including resource: META-INF/MANIFEST.MF]
[Adding property key: Manifest-Version value: 1.0]
[Adding property key: Ant-Version value: Apache Ant 1.6.5]
[Adding property key: Created-By value: 1.5.0_06-b05 (Sun Microsystems Inc.)]
[Adding property key: MIDlet-Name value: PickyMidlet]
[Adding property key: MIDlet-Version value: 1.0.0]
[Adding property key: MIDlet-Vendor value: Sun Microsystems Inc]
[Adding property key: MIDlet-1 value: , , org.sunspotworld.demo.PickyMidlet]
[Adding property key: MicroEdition-Profile value: IMP-1.0]
[Adding property key: MicroEdition-Configuration value: CLDC-1.1]
Created suite and wrote it into image.suite


--------------------------------------------------------------------
Hits   -   Class:98.56%  Monitor:92.61%  Exit:100.00%  New:98.80%
GCs: 3 full, 0 partial
** VM stopped: exit code = 0 ** 
Moving 1 file to C:\Program Files\Sun\SunSPOT\Demos\PickyMidlet\suite
Moving 1 file to C:\Program Files\Sun\SunSPOT\Demos\PickyMidlet\suite
Deleting: C:\Program Files\Sun\SunSPOT\Demos\PickyMidlet\image.suite.api
Waiting for target to synchronise... 
(please reset SPOT if you don't get a prompt)
[waiting for reset] 

Sun SPOT bootloader (1046-20060825) 
SPOT serial number = 0014.4F01.0000.XXXX
About to flash to slot 0
Writing imageapp3790.bintemp(2600 bytes) to COM6
.....................
Download operation completed successfully
Writing Configuration(1080 bytes) to COM6
.........
Download operation completed successfully

Exiting
Deleting: C:\Program Files\Sun\SunSPOT\sdk\temp\spot-temp-47675404
jar-deploy:
BUILD SUCCESSFUL (total time: 8 seconds)

 

You should note the line with the 16-digit SPOT serial number (SPOT serial number = 0014.4F01.0000.XXXX), which tells you the unique identification number for that particular Sun SPOT device. This will be useful later when it comes to creating more complex applications.

Now that you've successfully deployed the midlet to the Sun SPOT device, it's finally time to see whether your your Java app can actually "feel the rain" on its skin, or at least in this case, tell the temperature and light intensity of its surroundings.

I posted below the output of running this midlet. As you can see, the midlet first detected a temperature of 30 degrees and zero light (since the Sun SPOT device was first placed underneath my desk). I then took it out, and a minute later it registered an increase in light intensity. Since I was feeling somewhat emotional about all this (oh, the humanity!) , I cupped the Sun SPOT device in my closed hand and this increased the temperature to 33, then 34 degrees celsius, which seemed a bit too hot for the midlet!

init:
Using Sun SPOT device on port COM6
Waiting for target to synchronise... 
(please reset SPOT if you don't get a prompt)
[waiting for reset] 

Sun SPOT bootloader (1046-20060825) 
SPOT serial number = 0014.4F01.0000.XXXX

Squawk VM Starting (2006-08-25:10:48)...
Detected hardware type eSPOT-P2
PCTRL-1.70
EDEMOBOARD_REV_0_2_0_0
Starting OTACommandServer
My IEEE address is 0014.4F01.0000.0843
Registering protocol manager 'radiogram'
Adding radiogram connection for Server on port 8
[EDemoBoard] HARDWARE_REV: 5.0
Current temperature is 30 degrees.
Ahhh, that's just right!
Current light level is 0
Current temperature is 30 degrees.
Ahhh, that's just right!
Current light level is 41
Current temperature is 31 degrees.
It's too hot in here!
Current light level is 0
Current temperature is 33 degrees.
It's too hot in here!
Current light level is 0
Current temperature is 34 degrees.
It's too hot in here!
Current light level is 23


--------------------------------------------------------------------
Hits   -   Class:95.76%  Monitor:91.66%  Exit:100.00%  New:98.63%
GCs: 2 full, 0 partial
** VM stopped: exit code = 0 ** 


Exiting
Deleting: C:\Program Files\Sun\SunSPOT\sdk\temp\spot-temp-118124872
run:
BUILD SUCCESSFUL (total time: 5 minutes 0 seconds)


Sun SPOT and Java ME (J2ME).

return to previous page.

Copyright © 2007  RML. Java ME and other terms are trademarks or copyright of Sun Microsystems and/or other companies. Legal Stuff.