ohiofulvousΛογισμικό & κατασκευή λογ/κού

15 Αυγ 2012 (πριν από 5 χρόνια και 11 μήνες)

229 εμφανίσεις

Lab 3
: HTTP Access from a SPOT

Background Reading:

SunSPOT Developer's Guide, pages 41

These two pages of the Developer's Guide demonstrate how
to open and use HTTP connections on SPOTs. This lab is based on the code provided here, so it is useful

to read this beforehand.

Introduction to fetching files with HTTP in Java:
. Read all of section 2: “HTTP
Questions”. This

will introduce you to using HTTP connections with Java's URL and URLConnection
objects. It will also provide you with some good
know details about working with HTTP in Java and
things you might encounter.

Sun SPOT Sun Student Course, Section 4: HTTP P
rotocol Support.

In Sun’s Sun SPOT course at
, there is a section on HTTP protocol support in section 4 (“Programming
Sun SPOTs”). While this brief introduction to using HTTP over
the SPOTs may mostly reiterate things
covered in the Developer’s Guide, it is worth reading both for the recap and for additional details not
covered elsewhere, such as how to run the socket
proxy from NetBeans.

Prelab Questions:


What are the steps and cl
asses used to set up an HTTP connection and receive a file in normal
Java networking and with a SPOT?


When reading characters from an InputStream, how does one know when to stop (no more
chars are available to be read)?


You've seen how t
o perform radio communication between SPOTs. Now we see an example of an
application opening and using HTTP connections. The program that we create will grab an HTML file
from a web server with the HTTP protocol. We will then have the SPOT parse the pag
e and flash its
LED's whenever certain tags are encountered. Obviously SPOTs do not have direct connections to the
Internet. To use HTTP, a basestation must be running from a PC with access to the Internet, and the
Socket Proxy program must be started.

sing HTTP Connections with a SPOT: HtmlRetriever


Start new project.

First let's go ahead and start a new project for our HTTP application. This
time we won't be starting from any preexisting project's code, so
go to File
>New Project and
choose for you
r project to be a “Sun SPOT Application.”

For the project name, I chose
, but if you prefer another name, you are welcom
e to use that one instead.

will automatically use the project name for the name of the project folder unless you

tell it to do otherwise. You can place the project within the Demos directory if you want, but
might be a better idea to make a new folder
, calling it MyProjects or [your name]Projects or
something along those lines, and
place it in the main “SunSPOT”




up from
the “Demos” folder). You will then have a place to store all your future projects as well (you
might want to move your RadioCount project there, too).


Review the page retrieval code.

You should have already read the brief s
ection in the SPOT
Developer's Guide about opening and using HTTP connections. Provided (page 41) is some
example code that will open a connection, read an HTML page and display it, and then close the
connection. For convenience, this code is pasted belo
w. Notice how similar establishing our
HTTP connection is to how we set up our Radiogram connection in the last lab (and how using
the Radiostream protocol works as well). To get our connection we call just
like before; the only differen
ce is that this time, we supply a URL string as the argument and
assign the returned connection as an HttpConnection. We then use
connection.openInputStream() to set up an InputStream, from which we will read in our HTML
file one character at a time. As
the characters are read from the InputStream, we place them in
a standard StringBuffer object (“ch”, our temp variable that holds each character when it is read,
is declared as an int, but the value is cast to a char when it is appended to the buffer). On
ce the
InputStream is empty (<= 0), the program prints out the contents of the buffer, which
will display the same HTML source that one's browser receives when pointed to
Lastly, the InputStream and HttpConnection are both closed.

HttpConnection connection =

connection.setRequestProperty("Connection", "close");

InputStream in = connection.openInputStream();

ringBuffer buf = new StringBuffer();

int ch;

while ((ch = > 0) {







Prepare the startApp() method.

open up the source file for your new project


has provided you, called “” It would make sense to rename this
file to coincide with the name of your project, but is not necessary. If you wish to rename it,
click on the source file and select refactoring

This will bring up a dialog where
you can change the name of the file (and the class inside). After you enter the desired name,
click “next.” The output window at the bottom of the screen will now display a refactoring tree.
Click the “Do Refactoring
” button, and the file and class will be renamed. Inside the source file,
you will notice that

has taken care of most of the necessary imports for you, and has
given you three methods. The only method that has any code in it so far is startApp(
); you have
probably already guessed that this is the starting point of all Sun SPOT applications, similar to
main() in normal Java programs. For the HtmlRetriever, you can either put the code that
establishes the connection, grabs the page, and parses i
t (provided later) directly into startApp()
or create another method that is called from startApp(). The latter approach is usually
preferred, since it is considered cleaner to keep your startApp() method as short as possible, and
provide important code p
ieces with their own methods. Regardless of what you choose to do,
we need to clean up the contents of startApp() that we have been given. You can
get rid of


in startApp().

NetBeans should’ve created the array of LED object
s (of type ITriColorLED) as a class field for
you. As of the Blue SDK, this should be set up properly in a new project for you so that you
don’t have to change anything, however older versions automatically placed this as a local
variable in the startApp(
) method instead of as a field, so make sure it is in the correct place.

this line
inside the class, but outside of any method

private ITriColorLED
[] leds
= EdemoBoard.getInstance().getLEDs();

One last thing you will need to do as p
reparation is to
add the following import



Add the flashLights() method
. After our application reads in a web page it will parse the HTML
file and flash its LEDs when we tell it to (when certain tags

are encountered). We need to
provide a method to do this, so here it is:

protected void flashLights(int num, LEDColor color) {

for(int i=0; i < 8; i++) {



for(int i=0; i < num; i++) {

for(int j=0; j < 8; j++) {




for(int k=0; k <8; k++) {






It should be
pretty clear what is happening here. First we set the color of the LEDs (all eight of
them), based on the “color” parameter. Then we turn each LED on, wait a little bit, and then
turn them off. One tells flashLights() how many times to flash the LED's w
ith the “num”


Add the rest of the code
. Now all we have to do is add the code that opens an HTTP connection,
uses an InputStream to grab the page and place it in a StringBuffer, and finally goes through the
buffer and flashes the lights green ev
ery time an opening or closing script tag (“</script>” or
“<script”) is encountered and blue whenever an image occurs (“<img “). Much of the code is
identical to the Developer's Guide example. Here we use a second StringBuffer object to hold
the current
word as we go through the page (stored in “buf”) and check for our target tags
whenever whitespace characters (a newline or a space) occur. This code first has the lights flash
orange right before it starts parsing the web page, then flashes three times w
hen it finds either
of our two target strings, and flashes the lights red once after finding a tag to separate different
occurrences of the same tag.
Place this code either directly in startApp() or in another method
that you have startApp() call
. If you

leave it as is, this code will only parse the page once; if you
want it to happen more than once, you can placing the parsing code (the “for” loop) inside a
new loop and do it as many times as you wish.

HttpConnection connection =


connection.setRequestProperty("Connection", "close");

InputStream in = connection.openInputStream();

StringBuffer buf = new StringBuffer();

StringBuffer word = new StringBuffer

flashLights(2, LEDColor.ORANGE);

int ch;

while ((ch = > 0) {



for(int i=0; i < buf.length(); i++) {

char c = buf.charAt(i);

if(c == ' ' || c == '
n') {

int flashes = 3;

if (word.toString().equals("</script>") || word.toString().equals("<script")) {

flashLights(flashes, LEDColor.GREEN);

flashLights(1, LEDColor.RED);

} else if (word.toString().equals("<img")) {

flashLights(flashes, LEDColor.BLUE);

flashLights(1, LEDColor.RED);



} else {

word.append((char) c);






Start the Socket Proxy application
. Now its time to
plug in the basestation

and start the Socket
Proxy program. Once your basestation is connected to the PC,
start a shared basestation with
the SPOT Manager.

open up a command line, navigate to any project folder
OnSPOT will do, or even better, use
the folder of your current project), and

run t
he command “ant socket

Socket Proxy is
running, you should be ready to deploy and test your application.

Note that you can also start
the socket proxy application (in either stan
dard or gui mode) from NetBeans

by selecting a
project’s build.xml f
ile, right
clicking and go

to “R
un T

and then selecting

proxy” or “socket

Instead of right
clicking and using run target, you can also click
the plus sign next to build.xml to expand a list of all runnable targets.
This is co
vered in the Sun
Student Course.


Deploy and test the application
. Its time to check out what we've done.
Deploy your new
application to a SPOT

and see what happens. You should see your SPOT flash its lights blue and
green a number of times in sets of
four flashes. As of this writing, there are three places where
</script> tags occur on
, and many more occurrences of “<img .” Open
up a web browser and go to view
>source (or something sim
ilar, depending on your browser);
you should be able to determine which tag is making the SPOT flash its lights each time.



Add functionality to recognize more tags (or other frequently occurring strings), and
assign a new color to each. Do thi
s enough, and you will get quite a colorful display. Try
having your SPOT access different sites and see how the results change. You could also
have your SPOT parse several pages one after another on one run (make the URL string
an argument to your method
and call it several times with different values in


Have your program use the Radiogram protocol to send out messages to another SPOT
when special strings encountered, sending it the arguments to flashLights(). You can
make both SPOTs flash th
eir LEDs on each tag, only have the remote SPOT (the one that
is not parsing the page) do the
flashing, or alternate

which SPOT is to flash. You will
need to create a new application for the second SPOT that includes the flashLights()
method and allows th
e SPOT to receive Radiograms that contain the arguments to
flashLights(). Come up with some ideas for utilizing even more SPOTs, or to make sure
your SPOTs only act on communication from each other, and not SPOTs programmed by
other groups (as in last lab
's challenge).


The goal of this lab was to demonstrate how SPOTs can interact with web sites over
HTTP connections. You should be getting more comfortable writing SPOT applications and
starting to become familiar with the code behind common S
POT tasks, like working with the
LEDs and opening and using connections for various protocols.