Building the Web of Things with Sun SPOTs

  • 3,813 views
Uploaded on

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 …

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.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
3,813
On Slideshare
0
From Embeds
0
Number of Embeds
4

Actions

Shares
Downloads
113
Comments
0
Likes
4

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Building the Web of Things with Sun SPOTs Vipul Gupta and David G. Simmons, Sun Labs, Oracle vipul.x.gupta@oracle.com, david.g.simmons@oracle.com Ver: 20100921180500 JavaOne 2010, Hands-on Lab
  • 2. 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
  • 3. Background • People have been connecting “things” to the Internet even before the “Web” 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 3
  • 4. 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
  • 5. 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 OAuth SensorML Microformats 802.15.4 SWE ROLL 6lowPAN CHTTP EXI RHTTP Webhooks CoRE 5
  • 6. 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
  • 7. Background • People have been connecting “things” to 10 fool-proof predictions for the Internet in 2020 the Internet even before the “Web” 3. The Internet will be a network of things, not computers. • This trend is accelerating: phones, As more critical infrastructure gets hooked up household appliances, sensor platforms, to the Internet, the Internet is expected to ambient devices, energy meters, health become a network of devices rather than a and fitness devices, asset tracking network of computers.Today, the Internet has around 575 million host computers, according to the CIA World Factbook 2009. But the NSF • Commercial entities are getting involved is expecting billions of sensors on buildings and bridges to be connected to the Internet for such uses as electricity and security • Lots of standards activities: IEEE, IETF, monitoring. By 2020, it's expected that the IPSO, OGC, WWW number of Internet-connected sensors will be orders of magnitude larger than the number of users. • Recognition in mainstream media 7
  • 8. 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 Connected, smarter living 8
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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 More Info: - Roy Fielding’s Ph.D. Thesis (http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm) - REST Wiki (http://rest.blueoxen.net/) 12
  • 13. 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
  • 14. REST Examples • Create a new resource, e.g. deploy an application POST /apps HTTP/1.1 Content-Type: application/binary Client Content-Length: 8914 Sun SPOT <application binary> HTTP/1.1 201 Created Location: /apps/SensorSampler • Delete a resource, e.g. undeploy an application Client DELETE /apps/SensorSampler HTTP/1.1 Sun SPOT HTTP/1.1 200 OK 14
  • 15. REST Examples (cont’d) • Read a resource, e.g. read the light sensor reading GET /light HTTP/1.1 Client Accept: */* Sun SPOT HTTP/1.1 200 OK Content-Type: text/plain Content-Length: 3 138 • Update a resource, e.g. change color of LED 4 PUT /leds/4 HTTP/1.1 Content-Type: text/plain Client Content-Length: 7 Sun SPOT 0,255,0 HTTP/1.1 200 OK 15
  • 16. 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
  • 17. 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) Sun SPOT Uncompressed Compressed Client GET /spot-5317/temp HTTP/1.1 Accept: */* 13 bytes Host: localhost:8080 0000 - 68 36 47 2f 74 65 6d 70-00 0e 00 00 00 h6G/temp..... Content-Length: 0 User-Agent: curl/7.19.7 ... zlib/1.2.3 HTTP/1.1 200 OK 18 bytes Content-Type: text/plain 0000 - 48 36 40 11 b0 01 0a 00-3c 0e 00 05 00 38 39 2e H6@.....<....89. Cache-Control: max-age=60 0010 - 31 35 15 Content-Length: 5 89.15 17
  • 18. Network Topology Constraints • Device could be behind firewall/NAT, might move • Use relay, with “long-poll” and Reverse HTTP (draft-lentczner-rhttp-00) Sun SPOT Client relay.net POST /spot-5317 HTTP/1.1 Upgrade: PTTH/1.0 Connection: Upgrade Host: relay.net HTTP/1.1 101 Switching Protocols Upgrade: PTTH/1.0 Connection: Upgrade GET /spot-5317/light HTTP/1.1 Host: relay.net GET /spot-5317/light HTTP/1.1 HTTP/1.1 200 OK HTTP/1.1 200 OK Connection: close Connection: close Content-Length: 3 Content-Length: 3 216 216 18
  • 19. Energy Constraints • Devices sleep periodically to conserve battery • Use sleep-proxy to queue requests, cache responses zz z Sleep zz zz proxy Sun SPOT Client (sleep notification) GET /spots/01AB/temp HTTP/1.1 Cache-Control: max-age=60 HTTP/1.1 200 OK Age: 22 Content-Length: 5 86.45 PUT /spots/01AB/leds/5 HTTP/1.1 Content-Length: 7 0,255,0 HTTP/1.1 202 Accepted Retry-After: 45 Location: spots/01AB/requests/1cqfw 19
  • 20. 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) <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 20
  • 21. Notifications • Webhooks: an HTTP callback in the form of a POST Client postbin.org Sun SPOT HEAD /spots/01AB/light HTTP/1.1 HTTP/1.1 200 OK Link: </spots/01AB/light/web-hooks>, rel=”subscriptions” POST /spots/01AB/light/web-hooks HTTP/1.1 Notification-Type: UPDATED http://postbin.org/1c5r2aq HTTP/1.1 201 CREATED Location: /spots/01AB/light/web-hooks/1234 Link: </spots/01AB/light>, rel=”resource” POST /postbin.org/1c5r2aq HTTP/1.1 ... 21
  • 22. 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
  • 23. 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
  • 24. 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 Built to Inspire! (search for “spaughts” on Secure Flickr/YouTube) Built-in high grade ECC public key cryptography, user-friendly key management 24
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. Web Applications on Sun SPOTs • Web applications are developed in a manner very similar to servlets • Applications are hosted in a “Nano” app server WebApp1 WebApp2 ... /app1 /app2 • Small footprint (~40KB) web application container • Runs on SPOT and host MetaApp /.well-known • WebApplications register to handle parts NanoAppServer of the URL subspace RHTTPHandler • Supports compressed HTTP and UDP6Handler TCP6Handler UDPHandler TCPHandler multiple request channels • Built-in “MetaApp” handles /.well-known (RFC 5785) 29
  • 30. HOL Setup Gateway HTTP HTTP/CHTTP TCP TCP/UDP IP IPv6 6LoWPAN Ethernet/WiFi/... 802.15.4 cURL: see curl.haxx.se 30
  • 31. 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
  • 32. Dashboard Id Name Battery status Status panel Last heard Success ratio Light panel Light Readings LED panel LED Setting 32
  • 33. Here the four SPOTs (from L to R) have completed Exercise 2, 3, 4 and 5 respectively. 33
  • 34. Here the four SPOTs (from L to R) have completed Exercise 2, 3, 4 and 5 respectively. 34
  • 35. 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
  • 36. Exercise 1: “Flashlight” Application (20 mins) 36
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. Exercise 1: Running the Flashlight Application • 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 ... 40
  • 41. Exercise 1: Running the Flashlight Application ... -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] 41
  • 42. Exercise 1: Running the Flashlight Application -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 42
  • 43. 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
  • 44. Exercise 2: RESTful Web Application on SPOTs (20 mins) 44
  • 45. Exercise 2: Anatomy of a Web Application public class Status extends WebApplication { • Define its processRequest() ... public HttpResponse processRequest(HttpRequest request) throws IOException { • (Optionally) define isAuthroized() 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; } } } 45
  • 46. Exercise 2: Anatomy of a Web Application public class WoTServer extends MIDlet { • Define its processRequest() protected void startApp() throws MIDletStateChangeException { try { NanoAppServer nas = new NanoAppServer(); • (Optionally) define isAuthroized() nas.registerApp("/status", new Status("n=Access statusnsh=s")); nas.registerApp("/props", new PropertiesManager("n=Properties managernsh=pnd=http://bit.ly/aa8iOZ")); if (WoTConstants.SVC_CONNECTION_TYPE.equals("udp")) { • Register application with app server, new UDP6Handler(WoTConstants.TCP_UDP_SVCPORT, nas).start(); specifying } else { new TCP6Handler(WoTConstants.TCP_UDP_SVCPORT, nas).start(); } ... • URL to handle } catch (IOException ex) { ex.printStackTrace(); } } • properties, e.g. name, protected void pauseApp() { } description, short URL protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { } } 46
  • 47. 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 pointing your browser at http://address:port/spot-xxxx/.well-known/r URL Name /props, /p Properties /status, /s Status /blink, /b Blink LEDs } Try accessing http://address:port/spot-xxxx/.well-known/r?sh=p Last four hex-digits (Hint: ‘sh’ denotes ‘short URL’) 30D1 • 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 *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. 47
  • 48. Exercise 2: Sample Interactions (/.well-known) • List available services: % 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 OK content-type:text/html connection:close cache-control:max-age=60 content-length:424 What do you notice if you retry these two shell commands again soon after their previous invocation? 48
  • 49. Exercise 2: Sample Interactions (/props) • Read system properties: % 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", } • Create a new system property: % 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", } 49
  • 50. Exercise 2: Sample Interactions (/status) • Read status (name, battery level, charging, uptime, endnode): % curl --request GET “http://address:port/spot-xxxx/status” { n:"Louie", b:36, c:"n", u:2169473, e:"y" } • Other operations: % 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 50
  • 51. Exercise 2: Sample Interactions (/blink) • Read operation: % curl --request GET --dump-header “hdrs.txt” “http://address:port/spot-xxxx/blink” Client Error: 405 Method Not Allowed % more hdrs.txt HTTP/1.1 405 Method Not Allowed content-type:text/plain connection:close age:39 cache-control:max-age=260 allow:POST content-length:36 • Try POST: % curl --request POST --data “255,255,0” “http://address:port/spot-xxxx/blink” Successful: 200 OK causes SPOT to blink its LEDs yellow. 51
  • 52. 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
  • 53. Exercise 3: Light Sensor as a Web Resource (10 mins) 53
  • 54. 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
  • 55. Sample Interaction (/light) % curl --request GET “http://address:port/spot-xxxx/light” --dump-header “hdrs.txt” 49 % cat hdrs.txt HTTP/1.1 200 OK content-type:text/plain connection:close cache-control:max-age=20 content-length:2 % curl --request GET “http://address:port/spot-xxxx/light” --dump-header “hdrs.txt” 49 % cat hdrs.txt HTTP/1.1 200 OK content-type:text/plain connection:close age:5 cache-control:max-age=14 content-length:2 % curl --request DELETE “http://address:port/spot-xxxx/light” Client Error: 405 Method Not Allowed 55
  • 56. 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
  • 57. Exercise 4: LEDs as a Web Resource (15 mins) 57
  • 58. 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
  • 59. 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.txt Client Error: 405 Method Not Allowed % more hdrs.txt HTTP/1.1 405 Method Not Allowed content-type:text/plain connection:close allow:GET, PUT content-length:36 59
  • 60. 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
  • 61. Exercise 5: Adding Authentication (10 mins) 61
  • 62. 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
  • 63. Exercise 5: Adding Authentication /* * 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 } 63
  • 64. 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 Unauthorized content-type:text/plain connection:close www-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
  • 65. 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 Download the Sun SPOT SDK from http://www.sunspotworld.com/ and experiment with the bundled “WebOfThings” demo, e.g. try RHTTP 65
  • 66. Thank You! (and send us your feedback) This lab would not have been possible without the work of Sun SPOT team members, both past and present. 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) 66