building the web of things with sun spots

66
Building the Web of Things with Sun SPOTs Vipul Gupta and David G. Simmons, Sun Labs, Oracle [email protected] , [email protected] JavaOne 2010, Hands-on Lab Ver: 20100921180500

Upload: benaam

Post on 05-Dec-2014

4.330 views

Category:

Technology


4 download

DESCRIPTION

In just a few years, the number of Internet-connected "things" (home appliances, smart energy meters, health monitors, sensors) is predicted to be orders of magnitude larger than the number of users and traditional computers. The Web of Things is a vision where everyday objects are seamlessly integrated into the World Wide Web (WWW) using well-known standards and blueprints (e.g. URIs, HTTP and REST). This hands-on lab (presented at JavaOne 2010) introduces participants to the motivation, key concepts and relevant technologies behind this vision. Lab attendees will use the Sun SPOT wireless device (www.sunspotworld.com) developed at Sun Labs to learn how physical resources (e.g. light sensor, LEDs) can be exposed as web resources and manipulated via HTTP commands. Additional lab materials may be accessed at http://www.sunspotworld.com/S314730_Sun_SPOTs_Web_Of_Things/index.html.

TRANSCRIPT

Page 1: Building the Web of Things with Sun SPOTs

Building the Web of Things with Sun SPOTsVipul Gupta and David G. Simmons, Sun Labs, [email protected], [email protected]

JavaOne 2010, Hands-on LabVer: 20100921180500

Page 2: Building the Web of Things with Sun SPOTs

Agenda

• Background: From the Internet of computers to the Internet of things.

• The Web of Things: Vision, relevant technologies, challenges in constrained environments, examples.

• Introduction to Sun SPOTs: motivation, features.

• Lab overview and exercises:

• Sample “Flashlight” application on Sun SPOTs (Ex 1)

• RESTful web application on Sun SPOTs (Ex 2)

• Exposing the light sensor (Ex 3) and LEDs (Ex 4) as web resources

• Access control (Ex 5)

2

Page 3: Building the Web of Things with Sun SPOTs

Background

• People have been connecting “things” to the Internet even before the “Web”

3

More Info:

- Trojan room coffee pot

http://www.cl.cam.ac.uk/coffee/qsf/coffee.html

- Romkey & Hackett’s Internet Toaster, Interop ’90

http://www.savetz.com/yic/YIC11FI_6.html

- Robin Southgate, 2001

http://news.bbc.co.uk/2/hi/science/nature/1264205.stm

Page 4: Building the Web of Things with Sun SPOTs

Background

• People have been connecting “things” to the Internet even before the “Web”

• This trend is accelerating: phones, household appliances, sensor platforms, ambient devices, energy meters, health and fitness devices, asset tracking

4

Page 5: Building the Web of Things with Sun SPOTs

Background

• People have been connecting “things” to the Internet even before the “Web”

• This trend is accelerating: phones, household appliances, sensor platforms, ambient devices, energy meters, health and fitness devices, asset tracking

• Commercial entities are getting involved

• Lots of standards activities: IEEE, IETF, IPSO, OGC, WWW

5

6lowPAN802.15.4

ROLL

CoRE

SensorML

SWEEXI RHTTP

CHTTP

Webhooks

MicroformatsOAuth

Page 6: Building the Web of Things with Sun SPOTs

Background

• People have been connecting “things” to the Internet even before the “Web”

• This trend is accelerating: phones, household appliances, sensor platforms, ambient devices, energy meters, health and fitness devices, asset tracking

• Commercial entities are getting involved

• Lots of standards activities: IEEE, IETF, IPSO, OGC, WWW

• Recognition in mainstream media

6

’’

Page 7: Building the Web of Things with Sun SPOTs

Background

• People have been connecting “things” to the Internet even before the “Web”

• This trend is accelerating: phones, household appliances, sensor platforms, ambient devices, energy meters, health and fitness devices, asset tracking

• Commercial entities are getting involved

• Lots of standards activities: IEEE, IETF, IPSO, OGC, WWW

• Recognition in mainstream media

7

10 fool-proof predictions for the Internet in 2020

3. The Internet will be a network of things, not computers.

As more critical infrastructure gets hooked up to the Internet, the Internet is expected to become a network of devices rather than a network of computers.Today, the Internet has around 575 million host computers, according to the CIA World Factbook 2009. But the NSF is expecting billions of sensors on buildings and bridges to be connected to the Internet for such uses as electricity and security monitoring. By 2020, it's expected that the number of Internet-connected sensors will be orders of magnitude larger than the number of users.

Page 8: Building the Web of Things with Sun SPOTs

Motivation

• Comfort and entertainment -- smart environments (buildings, homes)

• Proactive health management -- both people and things (maintenance/repair)

• Better efficiency -- resource management (lower cost of heating/cooling)

• Timely access to information -- smart phones, environmental sensors

• Improved security and peace of mind -- accurate, responsive tracking of valuable assets

8

Connected, smarter living

Page 9: Building the Web of Things with Sun SPOTs

Commercial Opportunities

• “Things” or platforms for building “things”: (Arduino, BugLabs, Sun SPOT, TED, Chumby, Nabztag, Nike+iPod, Wattson, sensaware, Crossbow)

• Applications (PowerMeter, RunKeeper)

• Infrastructure components: gateways, relay services(therecorporation.com, iobridge.com, yaler.org)

• Platforms: middle-ware or hosted service for data collection and analysis (Pachube, Sensor.Network)

9

Page 10: Building the Web of Things with Sun SPOTs

Agenda

• Background: From the Internet of computers to the Internet of things.

• The Web of Things: Vision, relevant technologies, challenges in constrained environments, examples.

• Introduction to Sun SPOTs: motivation, features.

• Lab overview and exercises:

• Sample “Flashlight” application on Sun SPOTs (Ex 1)

• RESTful web application on Sun SPOTs (Ex 2)

• Exposing the light sensor (Ex 3) and LEDs (Ex 4) as web resources

• Access control (Ex 5)

10

Page 11: Building the Web of Things with Sun SPOTs

Web Of Things

• What? “A vision where everyday devices and objects are integrated into the Web using well-known standards and blueprints (URIs, HTTP, REST).”

“Seamless integration of physical and conceptual resources”

Also: “The physical web”, “the tactile web”

• How? - Connect device to Internet, - Embed web server, - Model resources as URIs

11

Page 12: Building the Web of Things with Sun SPOTs

REST (Representational State Transfer)

• Architectural style of the World Wide Web

• "The main idea of REST is to design applications which implement their functionality completely as a set of URI-addressable resources, with HTTP being the [uniform] access method for interacting with them. In such an application, there is no need for any special interface, the application fully blends into the Web ..." -- Erik Wilde, UC Berkeley Putting things to REST

12

More Info:

- Roy Fielding’s Ph.D. Thesis (http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm)

- REST Wiki (http://rest.blueoxen.net/)

Page 13: Building the Web of Things with Sun SPOTs

REST in a Nutshell

• Identify application “resources” using URIs.

• Each resource implements some subset of a uniform interface: POST (Create), GET (Read), PUT (Update), DELETE (Destroy). Response codes describe method success/failure.

• Representations (XHTML, XML, JSON), conceptually separate from resources, transferred in requests/responses.

• Representation includes metadata and links to related resources.

13

Page 14: Building the Web of Things with Sun SPOTs

REST Examples

14

POST /apps HTTP/1.1Content-Type: application/binaryContent-Length: 8914

<application binary>

HTTP/1.1 201 CreatedLocation: /apps/SensorSampler

• Create a new resource, e.g. deploy an application

• Delete a resource, e.g. undeploy an application

DELETE /apps/SensorSampler HTTP/1.1

HTTP/1.1 200 OK

ClientSun SPOT

Sun SPOTClient

Page 15: Building the Web of Things with Sun SPOTs

REST Examples (cont’d)

15

GET /light HTTP/1.1Accept: */*

• Read a resource, e.g. read the light sensor reading

• Update a resource, e.g. change color of LED 4

HTTP/1.1 200 OK

Client

Sun SPOT

Sun SPOTClient

HTTP/1.1 200 OKContent-Type: text/plainContent-Length: 3

138

PUT /leds/4 HTTP/1.1Content-Type: text/plainContent-Length: 7

0,255,0

Page 16: Building the Web of Things with Sun SPOTs

REST Benefits

• Simplifies integration of resources into the Web, making them accessible as part of a global information system.

• Ease building of apps on top of embedded devices, dynamic ad-hoc composite apps involving real-world devices (physical mashups)

• “Uniform interface” enables interaction with all sorts of devices via readily available software (browsers, cURL)

• “Layered system” supports intermediaries, great for addressing device/network constraints

• Get lots of features for free: caching, linking, security, bookmarking, searching, (HTTP utilized as an application protocol, not just transport).

16

Page 17: Building the Web of Things with Sun SPOTs

Network Bandwidth Constraints

• HTTP, XML are verbose. TCP connection setup/teardown adds overhead.

• Use caching, compression via binary encoding, use UDP, e.g. Efficient XML Interchange (http://www.w3.org/XML/EXI/), HTTP header compression (IETF CoRE, draft-tolle-core-ebhttp-00, draft-frank-6lowpan-chopan-00)

17

GET /spot-5317/temp HTTP/1.1Accept: */*Host: localhost:8080Content-Length: 0User-Agent: curl/7.19.7 ... zlib/1.2.3

0000 - 68 36 47 2f 74 65 6d 70-00 0e 00 00 00 h6G/temp.....13 bytes

0000 - 48 36 40 11 b0 01 0a 00-3c 0e 00 05 00 38 39 2e H6@.....<....89.0010 - 31 35 15

18 bytesHTTP/1.1 200 OKContent-Type: text/plainCache-Control: max-age=60Content-Length: 5

89.15

Uncompressed CompressedSun SPOT

Client

Page 18: Building the Web of Things with Sun SPOTs

Network Topology Constraints

• Device could be behind firewall/NAT, might move

• Use relay, with “long-poll” and Reverse HTTP (draft-lentczner-rhttp-00)

18

POST /spot-5317 HTTP/1.1Upgrade: PTTH/1.0Connection: UpgradeHost: relay.net

HTTP/1.1 101 Switching ProtocolsUpgrade: PTTH/1.0Connection: Upgrade

GET /spot-5317/light HTTP/1.1

GET /spot-5317/light HTTP/1.1Host: relay.net

relay.net

Sun SPOT

Client

HTTP/1.1 200 OKConnection: closeContent-Length: 3

216

HTTP/1.1 200 OKConnection: closeContent-Length: 3

216

Page 19: Building the Web of Things with Sun SPOTs

Energy Constraints

• Devices sleep periodically to conserve battery

• Use sleep-proxy to queue requests, cache responses

19

PUT /spots/01AB/leds/5 HTTP/1.1Content-Length: 7

0,255,0

HTTP/1.1 200 OKAge: 22Content-Length: 5

86.45

Sun SPOT

Client

z z z z zzz

HTTP/1.1 202 AcceptedRetry-After: 45Location: spots/01AB/requests/1cqfw

GET /spots/01AB/temp HTTP/1.1Cache-Control: max-age=60

Sleep proxy

(sleep notification)

Page 20: Building the Web of Things with Sun SPOTs

Discovery

• Finding/understanding what a “thing” provides, relationship to other things

• Bootstrapping: Well defined location for metadata (/.well-known, RFC 5785)

• Typed links: Use the “rel” attribute in links to describe relationships(draft-nottingham-http-link-header-10), e.g. Link: </>; rel=“http://example.net/foo’’

• Microformats (microformats.org)

20

<div class="vcard"> <div class="fn">Joe Doe</div> <div class="org">The Example Company</div> <div class="tel">604-555-1234</div> <a class="url" href="http://example.com/"> http://example.com/</a> </div>

See also: http://hueniverse.com/2009/11/the-discovery-protocol-stack-redux

Page 21: Building the Web of Things with Sun SPOTs

Notifications

• Webhooks: an HTTP callback in the form of a POST

21

HEAD /spots/01AB/light HTTP/1.1

POST /spots/01AB/light/web-hooks HTTP/1.1Notification-Type: UPDATED

http://postbin.org/1c5r2aq

HTTP/1.1 200 OKLink: </spots/01AB/light/web-hooks>, rel=”subscriptions”

HTTP/1.1 201 CREATEDLocation: /spots/01AB/light/web-hooks/1234Link: </spots/01AB/light>, rel=”resource”

Client

Sun SPOT

POST /postbin.org/1c5r2aq HTTP/1.1...

postbin.org

Page 22: Building the Web of Things with Sun SPOTs

Agenda

• Background: From the Internet of computers to the Internet of things.

• The Web of Things: Vision, relevant technologies, challenges in constrained environments, examples.

• Introduction to Sun SPOTs: motivation, features.

• Lab overview and exercises:

• Sample “Flashlight” application on Sun SPOTs (Ex 1)

• RESTful web application on Sun SPOTs (Ex 2)

• Exposing the light sensor (Ex 3) and LEDs (Ex 4) as web resources

• Access control (Ex 5)

22

Page 23: Building the Web of Things with Sun SPOTs

Sun SPOT Device

• Basic device has three layers• Battery

• Processor Board with Radio

• Sensor Board (application specific)

• Processor Board alone acts as a base-station

• User programs the device entirely in Java using standard Java tools

23

Page 24: Building the Web of Things with Sun SPOTs

Sun SPOT Capabilities/Technologies

Embedded Development Platform

Extremely flexible hardware and software package

Easy to program - Java top to bottom

Java Device Drivers

Connected - Wireless Communication

Mesh Networking

Over the Air Programming

Mobile

Built in Lithium Ion battery charged through USB

Aware and Active

Able to sense and affect surroundings

Secure

Built-in high grade ECC public key cryptography, user-friendly key management

24

Built to Inspire! (search for “spaughts” on

Flickr/YouTube)

Page 25: Building the Web of Things with Sun SPOTs

Sun SPOT Developer’s kit

• Two Full Sun SPOTs with eDemoSensor boards and batteries

• One base-station Sun SPOT

• Software

• Squawk VM

• Java SDK

• Netbeans

• USB cable, mounting clips

• Both hardware and software is open source

• www.sunspotworld.com

25

Page 26: Building the Web of Things with Sun SPOTs

Agenda

• Background: From the Internet of computers to the Internet of things.

• The Web of Things: Vision, relevant technologies, challenges in constrained environments, examples.

• Introduction to Sun SPOTs: motivation, features.

• Lab overview and exercises:

• Sample “Flashlight” application on Sun SPOTs (Ex 1)

• RESTful web application on Sun SPOTs (Ex 2)

• Exposing the light sensor (Ex 3) and LEDs (Ex 4) as web resources

• Access control (Ex 5)

26

Page 27: Building the Web of Things with Sun SPOTs

Exercise 1: “Flashlight” Application

• Shows Sun SPOTs ability to sense and respond to its environment. Application automatically turns on the LEDs when ambient light is low

• Shows how to access resources (sensors, LEDs, switches) on the Sun SPOT

• Shows how to build and deploy a simple application and monitor its output

• Uses NetBeans for illustration but SDK is IDE agnostic

27

Page 28: Building the Web of Things with Sun SPOTs

Exercise 2-5: Web Applications on Sun SPOT

• Learn about tools for building RESTful services on SPOTs

• Each exercise builds on the previous one, i.e. solution for an exercise is included in the code for the next exercise :-)

• Exercise 2: Experiment and interact with pre-defined services -- /.well-known (meta-information), /status (read-only), /props (read/update/delete) /blink

• Exercise 3: Develop a service for accessing the light sensor on SPOTs

• Exercise 4: Develop a service for accessing and updating LED color on SPOTs

• Exercise 5: Add authentication to the update operation in Exericse 4

28

Page 29: Building the Web of Things with Sun SPOTs

Web Applications on Sun SPOTs

• Web applications are developed in a manner very similar to servlets

• Applications are hosted in a “Nano” app server

• Small footprint (~40KB) web applicationcontainer

• Runs on SPOT and host

• WebApplications register to handle parts of the URL subspace

• Supports compressed HTTP and multiple request channels

• Built-in “MetaApp” handles /.well-known (RFC 5785)

NanoAppServer

...

RH

TTP

Han

dler

TCP

Han

dler

UD

PH

andl

er

TCP

6Han

dler

UD

P6H

andl

er

MetaApp/.well-known

Web

App

1/a

pp1

Web

App

2/a

pp2

29

Page 30: Building the Web of Things with Sun SPOTs

HOL Setup

Gateway

HTTP

TCP

IP

Ethernet/WiFi/...

HTTP/CHTTP

TCP/UDP

IPv6

6LoWPAN

802.15.4

30

cURL: see curl.haxx.se

Page 31: Building the Web of Things with Sun SPOTs

HOL Setup

• Lab attendees program SPOTs (far right)

• Gateway acts as protocol translator, caching agent and sleep proxy

• “Dashboard” web page makes periodic accesses to

• /spots on gateway for available SPOTs

• and for each SPOT on that list, it accesses

• spot-xxxx/status, spot-xxxx/light, spot-xxxx/leds

• Retrieved information is displayed graphically using Protovis*

*See http://vis.stanford.edu/protovis 31

Page 32: Building the Web of Things with Sun SPOTs

Dashboard

LED panel

Light panel

Status panel

32

Last heard

Battery status

Success ratio

Id

Name

LED Setting

Light Readings

Page 33: Building the Web of Things with Sun SPOTs

33

Here the four SPOTs (from L to R) have completed Exercise 2, 3, 4 and 5 respectively.

Page 34: Building the Web of Things with Sun SPOTs

34

Here the four SPOTs (from L to R) have completed Exercise 2, 3, 4 and 5 respectively.

Page 35: Building the Web of Things with Sun SPOTs

Agenda

• Background: From the Internet of computers to the Internet of things.

• The Web of Things: Vision, relevant technologies, challenges in constrained environments, examples.

• Introduction to Sun SPOTs: motivation, features.

• Lab overview and exercises:

• Sample “Flashlight” application on Sun SPOTs (Ex 1)

• RESTful web application on Sun SPOTs (Ex 2)

• Exposing the light sensor (Ex 3) and LEDs (Ex 4) as web resources

• Access control (Ex 5)

35

Page 36: Building the Web of Things with Sun SPOTs

36

Exercise 1:

“Flashlight” Application (20 mins)

Page 37: Building the Web of Things with Sun SPOTs

Exercise 1: Flashlight Application (page 1 of 3)

package org.sunspotworld;

import com.sun.spot.resources.Resources;import com.sun.spot.resources.transducers.ILightSensor;import com.sun.spot.resources.transducers.ISwitch;import com.sun.spot.resources.transducers.ISwitchListener;import com.sun.spot.resources.transducers.ITriColorLEDArray;import com.sun.spot.resources.transducers.LEDColor;import com.sun.spot.resources.transducers.SwitchEvent;import com.sun.spot.util.*;

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

/** * The manifest specifies this class as MIDlet-1, which means the VM * will call the startApp method of this class to start the application. */public class Flashlight extends MIDlet { private static int LOW_LIGHT_THRESHOLD = 60; private static LEDColor currentColor = LEDColor.WHITE; private static int currentColorIdx = 0; private static LEDColor[] colorChoices = { LEDColor.WHITE, LEDColor.GREEN, LEDColor.CYAN, LEDColor.YELLOW }; private ILightSensor lightSensor = null; private ITriColorLEDArray myLEDs = null; private ISwitch sw = null;

37

Page 38: Building the Web of Things with Sun SPOTs

Exercise 1: Flashlight Application (page 2 of 3)

protected void startApp() throws MIDletStateChangeException { int lightVal = 0;

System.out.println("Flashlight application starting ...\n" + ... + "Switch 1. Press Switch 2 to change LED color.\n");

// Get the lightsensor, the LED array and the switch as a resource ... lightSensor = (ILightSensor) Resources.lookup(ILightSensor.class); myLEDs = (ITriColorLEDArray) Resources.lookup(ITriColorLEDArray.class); // The resource lookup API supports tags ... this gets us Switch 2. sw = (ISwitch) Resources.lookup(ISwitch.class, "SW2");

if ((lightSensor == null) || (myLEDs == null) || (sw == null)) { System.err.println("Could not obtain necessary resources"); notifyDestroyed(); }

// Define & bind an anonymous switchlistener to change color on switch press sw.addISwitchListener(new ISwitchListener() { public void switchPressed(SwitchEvent evt) { currentColorIdx = (currentColorIdx + 1) % (colorChoices.length); currentColor = colorChoices[currentColorIdx]; System.out.println("New color is " + currentColor); }

public void switchReleased(SwitchEvent evt) { } });

38

Page 39: Building the Web of Things with Sun SPOTs

Exercise 1: Flashlight Application (page 3 of 3)

while (true) { // In a loop ... try { // Get light reading ... lightVal = lightSensor.getValue(); System.out.println("Light value is " + lightVal);

if (lightVal < LOW_LIGHT_THRESHOLD) { // turn on the LEDs if light is below predefined threshold for (int i = 0; i < myLEDs.size(); i++) { myLEDs.getLED(i).setColor(currentColor); myLEDs.getLED(i).setOn(); } } else { // otherwise, turn off the LEDs for (int i = 0; i < myLEDs.size(); i++) { myLEDs.getLED(i).setOff(); } } } catch (Exception e) { System.err.println("Caught " + e); e.printStackTrace(); }

Utils.sleep(500); } }

....}

39

Page 40: Building the Web of Things with Sun SPOTs

Exercise 1: Running the Flashlight Application

40

• To build, deploy and run this application, connect the SPOT via a USB cable to your computer and do one of the following:

• In NetBeans, right click on the project name “Exercise1” and choose “Run”

• In a terminal window, type the following command % ant compile deploy run

• Output is shown on next two slides ...

Page 41: Building the Web of Things with Sun SPOTs

41

... -run-spotclient-once: [java] SPOT Client starting... [java] [waiting for reset] ... [java] [waiting for reset] ... [java] (please reset SPOT 0014.4F01.0000.xxxx on port /dev/cu.usbmodem621)

... [java] Sun SPOT bootloader (yellow-100910) [java] SPOT serial number = 0014.4F01.0000.FF22 [java] Writing SPOT properties (349 bytes) to local SPOT on port /dev/cu.usbmodem621 [java] |============================================================| 100% [java] [java] [java] Using target file name: spotsuite://Sun_Microsystems_Inc/Exercise1 [java] Relocating application suite to 0x10900000 [java] About to flash from /Users/vgupta/Desktop/OldDesktop/Docs/JavaOne2010/S314730_Sun_SPOTs_Web_Of_Things/Exercises/Exercise1/suite/image [java] Writing imageapp4934778024996327784.bintemp (4140 bytes) to local SPOT on port /dev/cu.usbmodem621 [java] |====== | 12% [java] |============ | 24% .... [java] |========================================================= | 97% [java] |============================================================| 100% [java] [java]

Exercise 1: Running the Flashlight Application

Page 42: Building the Web of Things with Sun SPOTs

42

-run-spotclient-once: [java] SPOT Client starting... [java] [java] ** VM stopped: exit code = 0 ** [java] [java] Starting midlet 1 in spotsuite://Sun_Microsystems_Inc/Exercise1 [java] Flashlight application starting ... [java] To turn on the LEDs, cover the light sensor on the Sun SPOT. [java] The light sensor is the tiny white square just underneath [java] Switch 1. Press Switch 2 to change LED color. [java] [java] Light value is 23 [java] Light value is 24

Exercise 1: Running the Flashlight Application

Page 43: Building the Web of Things with Sun SPOTs

Agenda

• Background: From the Internet of computers to the Internet of things.

• The Web of Things: Vision, relevant technologies, challenges in constrained environments, examples.

• Introduction to Sun SPOTs: motivation, features.

• Lab overview and exercises:

• Sample “Flashlight” application on Sun SPOTs (Ex 1)

• RESTful web application on Sun SPOTs (Ex 2)

• Exposing the light sensor (Ex 3) and LEDs (Ex 4) as web resources

• Access control (Ex 5)

43

Page 44: Building the Web of Things with Sun SPOTs

44

Exercise 2:

RESTful Web Application on SPOTs (20 mins)

Page 45: Building the Web of Things with Sun SPOTs

Exercise 2: Anatomy of a Web Application

• Define its processRequest()

• (Optionally) define isAuthroized()

public class Status extends WebApplication { ...

public HttpResponse processRequest(HttpRequest request) throws IOException {

HttpResponse response = new HttpResponse(); String respStr = null; String name = Spot.getInstance().getPersistentProperties().getProperty("spot.name");

if (request.getMethod().equalsIgnoreCase("GET")) { respStr = " ... + Spot.getInstance().getPowerController().

getBattery().getBatteryLevel() + ...;

response.setStatus(HttpResponse.SC_OK); response.setHeader("Content-Type", "text/plain"); // Controls caching at gateway response.setHeader("Cache-Control", "max-age=30"); response.setBody(respStr.getBytes());

return response; } else { response.setStatus(HttpResponse.SC_METHOD_NOT_ALLOWED); response.setHeader("Allow", "GET");

return response; } }}

• Define its processRequest()

• (Optionally) define isAuthroized()

45

Page 46: Building the Web of Things with Sun SPOTs

Exercise 2: Anatomy of a Web Application

• Define its processRequest()

• (Optionally) define isAuthroized()

• Register application with app server, specifying

• URL to handle

• properties, e.g. name, description, short URL

public class WoTServer extends MIDlet { protected void startApp() throws MIDletStateChangeException {

try { NanoAppServer nas = new NanoAppServer(); nas.registerApp("/status", new Status("n=Access status\nsh=s")); nas.registerApp("/props", new PropertiesManager("n=Properties

manager\nsh=p\nd=http://bit.ly/aa8iOZ"));

if (WoTConstants.SVC_CONNECTION_TYPE.equals("udp")) { new UDP6Handler(WoTConstants.TCP_UDP_SVCPORT, nas).start(); } else { new TCP6Handler(WoTConstants.TCP_UDP_SVCPORT, nas).start(); }

...

} catch (IOException ex) { ex.printStackTrace(); } }

protected void pauseApp() { }

protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {

}}

46

Page 47: Building the Web of Things with Sun SPOTs

Exercise 2: Sample Interactions

• Replace address:port with a.b.c.d:8888*, xxxx with last four hex-digits in your SPOT’s Id (see the back of “fin”).

• Explore available services on your SPOT by pointingyour browser at http://address:port/spot-xxxx/.well-known/r

Try accessing http://address:port/spot-xxxx/.well-known/r?sh=p

(Hint: ‘sh’ denotes ‘short URL’)

• Click on service name for documentation. Clicking on service URL causes a “GET” on that service, Use cURL for other HTTP operations -- PUT, POST, DELETE

47

URL Name/props, /p Properties/status, /s Status/blink, /b Blink LEDs

Last four hex-digits30D1

}

*If you are following the lab exercises outside of the JavaOne hands-on lab, you’ll need to run the gateway code in Exercise/Gateway-onDesktop and replace a.b.c.d:8888 with the address and port printed by the gateway application.

Page 48: Building the Web of Things with Sun SPOTs

Exercise 2: Sample Interactions (/.well-known)

• List available services:

48

% curl --request GET --dump-header “hdrs.txt” “http://address:port/spot-xxxx/.well-known/r”<table><tr><th>URL</th><th>Name</th></tr><tr><td><a href="../props">/props</a>, <a href="../p">/p</a></td><td><a href="http://bit.ly/aa8iOZ">Properties</a></td></tr><tr><td><a href="../status">/status</a>, <a href="../s">/s</a></td><td><a href="http://bit.ly/8YtWQE">Status</a></td></tr><tr><td><a href="../blink">/blink</a>, <a href="../b">/b</a></td><td><a href="http://bit.ly/bPAzq1">Blink LEDs</a></td></tr></table>

% more “hdrs.txt”HTTP/1.1 200 OKcontent-type:text/htmlconnection:closecache-control:max-age=60content-length:424

What do you notice if you retry these two shell commands again soon after their previous invocation?

Page 49: Building the Web of Things with Sun SPOTs

Exercise 2: Sample Interactions (/props)

• Read system properties:

• Create a new system property:

49

% curl --request GET “http://address:port/spot-xxxx/props”{ "spot.diagnostics": "true", "spot.powercontroller.firmware.version": "PCTRL-1.105", ... "spot.sdk.version": "yellow-100910", "spot.hardware.rev": "6",}

% curl --request POST --data “spot.name: Louie” “http://address:port/spot-xxxx/props”{ "spot.diagnostics": "true", "spot.powercontroller.firmware.version": "PCTRL-1.105", ...

"spot.name": "Louie", ... "spot.sdk.version": "yellow-100910", "spot.hardware.rev": "6",}

Page 50: Building the Web of Things with Sun SPOTs

Exercise 2: Sample Interactions (/status)

• Read status (name, battery level, charging, uptime, endnode):

• Other operations:

50

% curl --request GET “http://address:port/spot-xxxx/status”{n:"Louie",b:36,c:"n",u:2169473,e:"y"}

% curl --request POST “http://address:port/spot-xxxx/status” or

% curl --request PUT “http://address:port/spot-xxxx/status” or

% curl --request DELETE “http://address:port/spot-xxxx/status”

Client Error: 405 Method Not Allowed

Page 51: Building the Web of Things with Sun SPOTs

Exercise 2: Sample Interactions (/blink)

• Read operation:

• Try POST:

causes SPOT to blink its LEDs yellow.

51

% curl --request GET --dump-header “hdrs.txt” “http://address:port/spot-xxxx/blink”Client Error: 405 Method Not Allowed

% more hdrs.txtHTTP/1.1 405 Method Not Allowedcontent-type:text/plainconnection:closeage:39cache-control:max-age=260allow:POSTcontent-length:36

% curl --request POST --data “255,255,0” “http://address:port/spot-xxxx/blink”Successful: 200 OK

Page 52: Building the Web of Things with Sun SPOTs

Agenda

• Background: From the Internet of computers to the Internet of things.

• The Web of Things: Vision, relevant technologies, challenges in constrained environments, examples.

• Introduction to Sun SPOTs: motivation, features.

• Lab overview and exercises:

• Sample “Flashlight” application on Sun SPOTs (Ex 1)

• RESTful web application on Sun SPOTs (Ex 2)

• Exposing the light sensor (Ex 3) and LEDs (Ex 4) as web resources

• Access control (Ex 5)

52

Page 53: Building the Web of Things with Sun SPOTs

53

Exercise 3:

Light Sensor as a Web Resource (10 mins)

Page 54: Building the Web of Things with Sun SPOTs

Exercise 3: Light sensor as a Web resource

• Create a simple web application (as described at http://bit.ly/aLqyNA) that responds to HTTP GETs on /light by returning the light sensor reading(Hint: See Exercise 1 for example code to retrieve light sensor reading.)

• Modifications required (look for lines starting XXX)

• HOLLightSensor.java: In processRequest(), modify respStr to return light sensor reading (Hint: See Exercise 1 for example code)

• WoTServer.java: In startApp(), add another call to nas.registerApp registering the light service implemented by HOLLightSensor (Hint: See code for pre-existing services -- blink, status, props)

• If successful, dashboard page will automatically retrieve and display light readings

54

Page 55: Building the Web of Things with Sun SPOTs

Sample Interaction (/light)

% curl --request GET “http://address:port/spot-xxxx/light” --dump-header “hdrs.txt”49

% cat hdrs.txtHTTP/1.1 200 OKcontent-type:text/plainconnection:closecache-control:max-age=20content-length:2

% curl --request GET “http://address:port/spot-xxxx/light” --dump-header “hdrs.txt”49

% cat hdrs.txtHTTP/1.1 200 OKcontent-type:text/plainconnection:closeage:5cache-control:max-age=14content-length:2

% curl --request DELETE “http://address:port/spot-xxxx/light” Client Error: 405 Method Not Allowed

55

Page 56: Building the Web of Things with Sun SPOTs

Agenda

• Background: From the Internet of computers to the Internet of things.

• The Web of Things: Vision, relevant technologies, challenges in constrained environments, examples.

• Introduction to Sun SPOTs: motivation, features.

• Lab overview and exercises:

• Sample “Flashlight” application on Sun SPOTs (Ex 1)

• RESTful web application on Sun SPOTs (Ex 2)

• Exposing the light sensor (Ex 3) and LEDs (Ex 4) as web resources

• Access control (Ex 5)

56

Page 57: Building the Web of Things with Sun SPOTs

57

Exercise 4:

LEDs as a Web Resource (15 mins)

Page 58: Building the Web of Things with Sun SPOTs

Exercise 4: LEDs as a Web resource

• Create a simple web application (as described at http://bit.ly/9C3rlP) that

• responds to HTTP GETs on /leds by returning the LED color setting

• responds to HTTP PUTs on /leds by changing the LED color setting

(Hint: See Exercise 1 for sample code to access the LED resource)

• Modifications required (look for lines starting XXX)

• HOLLEDController.java: In processRequest(), modify respStr to show LED setting in response to “GET” and fill out handling of “PUT” requests.

• WoTServer.java: Add another call to nas.registerApp registering the LED service implemented by HOLLEDController (Hint: See code for pre-existing services)

• If successful, dashboard page will automatically retrieve and display LED setting (LED settings can also be changed by pressing Switch 2)

58

Page 59: Building the Web of Things with Sun SPOTs

Sample Interaction (/leds)

% curl --request GET “http://address:port/spot-xxxx/leds” [255,0,0]

% curl --request PUT --data “[255,255,0]” “http://address:port/spot-xxxx/leds” Successful: 200 OK

% curl --request GET “http://address:port/spot-xxxx/leds” [255,255,0]

% curl --request POST --data “[255,255,0]” “http://address:port/spot-xxxx/leds” --dump-header “hdrs.txtClient Error: 405 Method Not Allowed

% more hdrs.txtHTTP/1.1 405 Method Not Allowedcontent-type:text/plainconnection:closeallow:GET, PUTcontent-length:36

59

Page 60: Building the Web of Things with Sun SPOTs

Agenda

• Background: From the Internet of computers to the Internet of things.

• The Web of Things: Vision, relevant technologies, challenges in constrained environments, examples.

• Introduction to Sun SPOTs: motivation, features.

• Lab overview and exercises:

• Sample “Flashlight” application on Sun SPOTs (Ex 1)

• RESTful web application on Sun SPOTs (Ex 2)

• Exposing the light sensor (Ex 3) and LEDs (Ex 4) as web resources

• Access control (Ex 5)

60

Page 61: Building the Web of Things with Sun SPOTs

61

Exercise 5:

Adding Authentication (10 mins)

Page 62: Building the Web of Things with Sun SPOTs

Exercise 5: Adding Authentication

• Add Basic HTTP Authentication so LED color changes require a password

• Modifications required (look for lines starting XXX)

• HOLLEDController.java: In isAuthorized(), look for and match authorization header against expected value for PUT requests. GET requests should be allowed without authorization checks.

• WoTServer.java:Replace xxxx with last four hex-digits of your SPOT Id in the “realm” specification.

62

Page 63: Building the Web of Things with Sun SPOTs

Exercise 5: Adding Authentication

63

/* * We only support HTTP Basic authentication which * sends a Base-64 encoding of "username:password" in the * "Authorization" header. * * General form: * Authorization: <authType> <authToken> * * Example: * Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== * ... */ public boolean isAuthorized(HttpRequest req) { /* XXX Uncomment the following lines to authenticate PUTs. Replace "Ali Baba" with * the authorized username and "open sesame" with the authorized password. */// String authorizedUser = "Ali Baba";// String authorizedPassword = "open sesame";//// if (req.getMethod().equalsIgnoreCase("PUT")) {// String auth = req.getHeader("Authorization");//// return ((auth != null) && auth.equalsIgnoreCase("Basic " +// Base64.encode(authorizedUser + ":" + authorizedPassword)));// }

return true; // GETs should still succeed }

Page 64: Building the Web of Things with Sun SPOTs

Sample Interaction w/ Authentication Enabled

% curl --request PUT --data “[0,255,255]” “http://address:port/spot-xxxx/leds” Client Error: 401 Unauthorized

% more hdrs.txt HTTP/1.1 401 Unauthorizedcontent-type:text/plainconnection:closewww-authenticate:Basic realm="spot-xxxx"content-length:30

% curl --request PUT --data “[0,255,255]” --user "Ali Baba:open sesame" --basic “http://address:port/spot-xxxx/leds” Successful: 200 OK

% curl --request GET “http://address:port/spot-xxxx/leds” // GET needs no auth[0,255,255]

64

Page 65: Building the Web of Things with Sun SPOTs

Conclusion

• The Internet is rapidly becoming the “Internet of Things”

• Reusing/adapting well known concepts and technologies makes it easy to incorporate everyday objects into the Web seamlessly

• Constrained devices like Sun SPOTs may require the introduction of a gateway

• Emerging technologies (e.g. HTML 5, Webhooks) and phenomenon (e.g. M2M, social networking) present interesting new opportunities

65

Download the Sun SPOT SDK from http://www.sunspotworld.com/ and experiment with the bundled “WebOfThings” demo, e.g. try RHTTP

Page 66: Building the Web of Things with Sun SPOTs

Thank You! (and send us your feedback)

Sun SPOT team members flanked by Sun executives Greg P and Jonathan Schwartz (from L to R): Pete St. Pierre, Derek White, Roger Meike, Randy Smith, David G. Simmons, Ron Goldman, Arshan Poursohi, Eric Arseneau, Vipul Gupta, Bob Alkire, Poorna Udupi (not shown)

This lab would not have been possible without the work of Sun SPOT team members, both past and present.

66