O’Reilly Ebooks—Your bookshelf on your devices! When you buy an ebook through oreilly.com, you get lifetime access to the book, and whenever possible we provide it to you in four, DRM-free file formats—PDF, .epub, Kindle-compatible .mobi, and Android .apk ebook—that you can use on the devices of your choice. Our ebook files are fully searchable and you can cut-and-paste and print them. We also alert you when we’ve updated the files with corrections and additions. Learn more at http://oreilly.com/ebooks/ You can also purchase O’Reilly ebooks through iTunes, the Android Marketplace, and Amazon.com. Getting Started with the Internet of Things Cuno Pfister Getting Started with the Internet of Things by Cuno Pfister Copyright © 2011 Cuno Pfister. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc. 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Print History: May 2011: First Edition. Editor: Brian Jepson Production Editor: Jasmine Perez Copyeditor: Marlowe Shaeffer Proofreader: Emily Quill Compositor: Nancy Wolfe Kotary Indexer: Angela Howard Illustrations: Marc de Vinck Cover Designer: Marc de Vinck The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. The Make: Projects series designations and related trade dress are trademarks of O’Reilly Media, Inc. The trademarks of third parties used in this work are the property of their respective owners. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-4493-9357-1 [LSI] Preface One of the most fascinating trends today is the emergence of low-cost microcontrollers that are sufficiently powerful to connect to the Internet. They are the key to the Internet of Things, where all kinds of devices become the Internet’s interface to the physical world. Traditionally, programming such tiny embedded devices required completely different platforms and tools than those most programmers were used to. Fortunately, some microcontrollers are now capable of supporting modern software platforms like .NET, or at least useful subsets of .NET. This allows you to use the same programming language (C#) and the same development environment (Visual Studio) when creating programs for small embedded devices, smartphones, PCs, enterprise servers, and even cloud services. So what should you know in order to get started? This book gives one possible answer to this question. It is a Getting Started book, so it is neither an extensive collection of recipes (or design patterns for that matter), nor a reference manual, nor a textbook that compares different approaches, use cases, etc. Instead, its approach is “less is more,” helping you to start writing Internet of Things applications with minimal hassle. The Platforms The .NET Micro Framework (NETMF) provides Internet connectivity, is simple and open source (Apache license), has hardware available from several vendors, and benefits from the huge .NET ecosystem and available know-how. Also, you can choose between Visual Studio (including the free Express Edition) on Windows, and the open source Mono toolchain on Linux and Mac OS X. There is an active community for NETMF at http://www.netmf.com/ Home.aspx. The project itself is hosted at http://netmf.codeplex.com/. Netduino Plus (http://www.netduino.com/netduinoplus) is an inexpensive NETMF board from Secret Labs (http://www.secretlabs.com). This board makes Ethernet networking available with a price tag of less than $60. It has the following characteristics: » A 48 MHz Atmel SAM7 microcontroller with 128 KB RAM and 512 KB Flash memory » USB, Ethernet, and 20 digital I/O pins (six of which can be configured optionally for analog input) » Micro SD card support » Onboard LED and pushbutton » Form factor of the Arduino (http://www.arduino.cc/); many Arduino shields (add-on boards) can be used » .NET Micro Framework preprogrammed into Flash memory » All software and hardware is open source There is an active community for the Netduino Plus (and NETMF) at http://forums.netduino.com/. All the examples in this book use the Netduino Plus. How This Book Is Organized The book consists of three parts: » Part I, Introduction The first part tells you how to set up the development environment and write and run a “Hello World” program. It shows how to write to output ports (for triggering so-called actuators such as LED lights or motors) and how to read from input ports (for sensors). It then introduces the most essential concepts of the Internet of Things: HTTP and the division of labor between clients and servers. In the Internet of Things, devices are programmed as clients if you want them to push sensor data to some service; they are programmed as servers if you want to enable remote control of the device over the Web. » Part II, Device as HTTP Client The second part focuses on examples that send HTTP requests to some services—e.g., to push new sensor measurements to the Pachube service (http://www.pachube.com) for storage and presentation. » Part III, Device as HTTP Server The third part focuses on examples that handle incoming HTTP requests. Such a request may return a fresh measurement from a sensor, or may trigger an actuator. A suitable server-side library is provided in order to make it easier than ever to program a small device as a server. » Appendix A, Test Server This contains a simple test server that comes in handy for testing and debugging client programs. » Appendix B, .NET Classes Used in the Examples This shows the .NET classes that are needed to implement all examples, and the namespaces and assemblies that contain them. » Appendix C, Gsiot.Server Library This summarizes the interface of the helper library we use in Part III. that Who This Book Is For This book is intended for anyone with at least basic programming skills in an object-oriented language, as well as an interest in sensors, microcontrollers, and web technologies. The book’s target audience consists of the following groups: » Artists and designers You need a prototyping platform that supports Internet connectivity, either to create applications made up of multiple communicating devices, or to integrate the World Wide Web into a project in some way. You want to turn your ideas into reality quickly, and you value tools that help you get the job done. Perhaps you have experience with the popular 8-bit Arduino platform (http://www.arduino.cc/), and might even be able to reuse some of your add-on hardware (such as shields and breakout boards) originally designed for Arduino. » Students and hobbyists You want your programs to interact with the physical world, using mainstream tools. You are interested in development boards, such as the Netduino Plus, that do not cost an arm and a leg. » Software developers or their managers You need to integrate embedded devices with web services and want to learn the basics quickly. You want to build up an intuition that ranges from overall system architecture to real code. Depending on your prior platform investments, you may be able to use the examples in this book as a starting point for feasibility studies, prototyping, or product development. If you already know .NET, C#, and Visual Studio, you can use the same programming language and tools that you are already familiar with, including the Visual Studio debugger. To remain flexible, you want to choose between different boards from different vendors, allowing you to move from inexpensive prototypes to final products without having to change the software platform. To further increase vendor independence, you probably want to use open source platforms, both for hardware and software. To minimize costs, you are interested in a platform that does not require the payment of target royalties, i.e., per-device license costs. If your background is in the programming of PCs or even more powerful computers, a fair warning: embedded programming for low-cost devices means working with very limited resources. This is in shocking contrast with the World Wide Web, where technologies usually seem to be created with utmost inefficiency as a goal. Embedded programming requires more careful consideration of how resources are used than what is needed for PCs or servers. Embedded platforms only provide small subsets of the functionality of their larger cousins, which may require some inventiveness and work where a desired feature is not available directly. This can be painful if you feel at home with “the more, the better,” but it will be fun and rewarding if you see the allure of “small is beautiful.” What You Need to Get Started This book focuses on the interaction between embedded devices and other computers on the Internet, using standard web protocols. Its examples mostly use basic sensors and actuators, so it is unnecessary to buy much additional hardware besides an inexpensive computer board. Here is a list of things you need to run all the examples in this book: » A Netduino Plus board (http://www.netduino.com/netduinoplus) » A micro USB cable (normal male USB-A plug on PC side, male micro USB-B plug on Netduino Plus side), to be used during development and for supplying power » An Ethernet router with one Ethernet port available for your Netduino Plus » An Internet connection to your Ethernet router » An Ethernet cable for the communication between Netduino Plus and the Ethernet router » A potentiometer with a resistance of about 100 kilohm and throughhole connectors » A Windows XP/Vista/7 PC, 32 bit or 64 bit, for the free Visual Studio Express 2010 development environment (alternatively, you may use Windows in a virtual machine on Mac OS X or Linux, or you may use the Mono toolchain on Linux or Mac OS X) NOTE: ! There are several sources where you can buy the hardware components mentioned above, assuming you already have a router with an Internet connection: » Maker SHED (http://www.makershed.com/) » Netduino Plus, part number MKND02 » Potentiometer, part number JM2118791 » SparkFun (http://www.sparkfun.com/) » Netduino Plus, part number DEV-10186 » Micro USB cable, part number CAB-10215 (included with Netduinos for a limited time) » Ethernet cable, part number CAB-08916 » Potentiometer, part number COM-09806 For more sources in the U.S. and in other world regions, please see http://www.netduino.com/buy/?pn=netduinoplus. It is also possible to add further sensors and actuators. Conventions Used in This Book The following typographical conventions are used in this book: » Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. » Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, data types, statements, and keywords. » Shows commands or other text that should be typed literally by the user. » Shows text that should be replaced with user-supplied values or by values determined by context. NOTE: ! This style signifies a tip, suggestion, or general note. Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CDROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Getting Started with the Internet of Things, by Cuno Pfister. Copyright 2011 Cuno Pfister, 978-1-4493-9357-1.” If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at permissions@oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at: http://oreilly.com/catalog/0636920013037 To comment or ask technical questions about this book, send email to: bookquestions@oreilly.com For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our website at: http://oreilly.com Safari® Books Online Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly. With a subscription, you can read any page and watch any video from our library online. Read books on your cell phone and mobile devices. Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features. O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com. Acknowledgments My thanks go to Brian Jepson, Mike Loukides, and Jon Udell, who made it possible to develop this mere idea into an O’Reilly book. It was courageous of them to take on a book that uses a little-known software platform, bets on a hardware platform not in existence at that time, and addresses a field that is only now emerging. Brian not only edited and contributed to the text, he also tried out all examples and worked hard on making it possible to use Mac OS X and Linux as development platforms. I would like to thank my colleagues at Oberon microsystems for their support during the gestation of this book. Marc Frei and Thomas Amberg particularly deserve credit for helping me with many discussions, feedback, and useful code snippets. Their experience was invaluable, and I greatly enjoyed learning from them. Marc’s deep understanding of REST architecture principles and its implementation for small devices was crucial to me, as was Thomas’s insistence on “keeping it simple” and his enthusiasm for maker communities like those of Arduino and Netduino. Both showed amazing patience whenever I misused them as sounding boards and guinea pigs. I could always rely on Beat Heeb for hardware and firmware questions, thanks to his incredible engineering know-how, including his experience porting the .NET Micro Framework to several different processor architectures. Corey Kosak’s feedback made me change the book’s structure massively when most of it was already out as a Rough Cut. This was painful, but the book’s quality benefited greatly as a result. I have profited from additional feedback by the following people: Chris Walker, Ben Pirt, Clemens Szyperski, Colin Miller, and Szymon Kobalczyk. I am profoundly grateful because their suggestions definitely improved the book. The book wouldn’t have been possible without the Netduino Plus, and Chris Walker’s help in the early days when there were only a handful of prototype boards. Whenever I had a problem, he responded quickly, competently, and constructively. I have no idea when he finds time to sleep. Last but not least, many thanks go to the team at Microsoft—in particular Lorenzo Tessiore and Colin Miller—for creating the .NET Micro Framework in the first place. Their sheer tenacity to carry on over the years is admirable, especially that they succeeded in turning the platform into a true open source product with no strings attached. 12/Handling Actuator Requests To change the state of a resource, a web client can send PUT requests. A PUT request contains a representation of the desired new state of the resource. In this chapter’s example, an LED’s state (on/off) is controlled through a web service, as illustrated in Figure 12-1. Figure 12-1. Architecture of LedController shows how to handle PUT requests; thus, it is a server program. Unfortunately, you cannot directly use a web browser as a client for sending PUT requests because web browsers are focused on GET requests. Later in this chapter you will see how you can write your own client program (in both C# and JavaScript versions) for testing the server. !NOTE: If you don’t mind learning your way around tools like cURL (http://curl.haxx.se/docs/) or the Poster add-on for Firefox (https://addons.mozilla.org/en-US/firefox/addon/poster/), you can initiate PUT requests with these as well. For example, with the cURL command-line utility—which is usually installed by default on Mac OS X and Linux—you could use a command like this to turn the LED on (be sure to change the URI to match your configuration): From HTTP Resources to Controlling Things The resource managed in this example has the meaning “desired state of the LED on the board.” Such a resource that accepts target values (or setpoints) is called a manipulated variable. When a server receives a PUT request for a manipulated variable resource, it takes the setpoint value contained in the request message body and feeds it to an actuator. In this example, the actuator is simply an LED. A server that supports a manipulated variable may or may not support GET requests, in addition to PUT requests, for this resource. A GET request may simply return the most recent PUT value. URIs of Manipulated Variables By convention, manipulated variables in this book are called in this case : In more complicated applications than this example here, it may not be certain that putting a target value will really have the desired physical effect. For example, if you send a PUT request to a manipulated variable for a valve, with “closed” as the desired state, there may be mechanical reasons why this desired state is not achieved (e.g., the valve may have become mechanically blocked). In such situations, it might make sense to additionally provide a measured variable (sensor) for the valve. This ; would result in two separate resources: one for the actuator and one for the sensor: The distinction between these two resources reflects the physical reality of a device that has both a sensor (producing the actual value) and an actuator (changing state based on the target value). You may also provide a more abstract combined resource. For example, “state of the fountain in my garden” returns the actual value of the fountain’s valve in response to a GET request, and accepts a target value for the valve as part of a PUT request: You can play with the resources until you find the most suitable design for your application. People like different ways to “see” into a system. For example, your parents may only be interested in a temperature given in degrees Celsius, whereas you may be interested in the raw values returned by the sensor—especially if your parents complain that the temperature values cannot be correct. Maybe the sensor is defective, or the algorithm that translates raw sensor values to human-readable engineering units is buggy. Then, it helps to provide both the raw value and the processed value as resources. LedController The structure of Example 11-1, (Example 12-1) is very similar to that of . Example 12-1. LedController The main differences between the two examples are that Example 12-1 uses an instance of ( ) instead of , and an instance of (created using C#’s initializer syntax that was explained in Chapter 10) instead of . A instance has a delegate property for the conversion from an HTTP message body to a setpoint object, and a delegate property for applying the setpoint to an actuator. must be compatible with this delegate type: and Library method with assigned to must be compatible with this delegate type: , so it can be assigned to is compatible with . is compatible . The method , so it can be Inside Gsiot.Server’s DigitalActuator Class The library class is implemented in namespace , as shown in Example 12-2. Example 12-2. DigitalActuator The purpose of this class is to provide a common interface for actuators—namely, a method that consumes new setpoints and is compatible with the delegate type , and with a “declarative” initialization mechanism like the one of . C#: Protecting You from Dangerous Conversions A variable declared with type accepts anything assigned to it. It is often used in libraries, which should be independent of the exact types that will occur in the various applications that use those libraries. In our case, it is the library and the parameter of . If you know that at some point in your program, a variable of type must contain a value of a particular type, you can cast it safely in the following way: Unlike some other languages, C# will never allow you to proceed with an erroneous type cast on objects. Such type casts will either generate error messages at compile time or exceptions at runtime. In the above example, the check is performed at runtime because the compiler has no way of knowing what you might assign to . By contrast, the following code results in an error at compile time: The following code results in an exception at runtime: As a friend likes to say: every beer bottle is a bottle, but not every bottle is a beer bottle. Similarly, every boiler setpoint is a setpoint (which is an object in turn), but not every setpoint is a boiler setpoint. The C# type system helps to catch many programming mistakes either at compile time or at runtime—and the earlier, the better. Inside Gsiot.Server’s ManipulatedVariable Class The library class is implemented in namespace , as shown in Example 12-3. Example 12-3. ManipulatedVariable The purpose of this request handler for manipulated variables is to separate the request processing from the representation used in the request ( ) and from the way new setpoints are consumed ( ). Test Client in C# To test your server with a client that runs on a computer, use the test client given in Example 12-4, which sends a PUT request to the server. You need to adapt the constant to the address of your device. The representation sent to the server is contained in constant . See what happens if you send the value as given below, or if you change it to or some unsupported value. !NOTE: This code won’t run on a Netduino Plus. You’ll have to run it on Windows using .NET, or on Mac OS X or Linux using Mono. Mono is an open source implementation of .NET that runs on several platforms. Example 12-4. LedControllerClient test client in C# The test client writes the server’s response to a console window and then waits for you to press Ctrl-C to quit it. Embed a JavaScript Test Client on the Netduino Web browsers are convenient HTTP clients because they are available on practically any platform, and also because they can download new programs (scripts) without extra installation hassles. The trick is that script code can be embedded in HTML pages, so ordinary HTTP GET requests are sufficient as download mechanisms for JavaScript programs. Since JavaScript can issue PUT requests, you can click buttons on a web page to turn your LEDs on and off! And since the Netduino Plus is functioning as a web server, you can serve this JavaScript directly from your .NET Micro Framework code! To include some JavaScript in an HTML document, add a XML element with the code shown in Example 12-5. (Example 12-6 shows the complete example.) Example 12-5. LedController test client in JavaScript, embedded in HTML This script creates a new object (short for “request”) or an equivalent ActiveX object for Internet Explorer 6 or newer. This object has a method that takes the HTTP method and the request URI as parameters, and a method for adding request headers. It also has a method , which sends the HTTP request back to your server (your Netduino Plus). !NOTE: as its name suggests. can send any kind of representation, not just XML The object is used in the function , which takes the request message content as a parameter and sends it back in an HTTP PUT message to the same server from which the JavaScript came. The body of the HTML page produces three buttons: Switch LED on, Switch LED off, and Bah. When you click on them, they call the function with the arguments , , or . In the first case, the request is meant to switch on the Netduino Plus’s onboard LED. In the second case, the request is meant to switch off the Netduino Plus’s onboard LED. In the third case, the request is meant to provoke an error situation (see the debug console for what happens when you click on it). The resulting web page looks like Figure 12-2. Figure 12-2. Simple web page for controlling an LED The entire program is given in Example 12-6, which encodes the script from Example 12-5 in one large string. Instead of loading the HTML from a file, the Netduino Plus will serve it up out of its memory in the body of the handler. Example 12-6. LedControllerHtml with embedded JavaScript In this example, note that two resources are supported: Another noteworthy aspect of the example is the use of verbatim strings. A verbatim string starts with an sign and is followed by a character. It ends at the first character that isn’t doubled. To allow characters in a verbatim string, two subsequent characters are interpreted as a single character. In a verbatim string there may be carriage returns, line feeds, tabulator characters, etc., that don’t need an escape sequence like normal strings. This can make verbatim strings more readable in some cases. Here is an example of a verbatim string: It is equivalent to this regular string: What You Should Know About HTTP PUT To change the state of a device’s actuator, you send it HTTP PUT messages. Like GET, PUT is defined as being idempotent, meaning that issuing the same PUT request multiple times has the same effect on the server’s resources as issuing it only once—assuming no one else changes the same resource. This is particularly relevant in one situation: suppose your client program has sent a PUT request, but it does not get back a response. After a while, the client will time out. What should happen then? If the request had been lost on its way to the server, your client could simply try again and send the PUT request a second time. But what if the request had been received by the server, was processed correctly, and only the response message got lost somewhere on the way back to your client? Sending the PUT request again would cause the resource to be manipulated a second time. What could be a huge problem is no problem at all if you design your PUT request handlers to be idempotent, in which case simply sending the same PUT request again is harmless. This is the beauty of RESTful web services with HTTP. Distributed systems, where clients and servers operate on different machines and are connected through sometimes-unreliable connections, are notoriously difficult to program correctly. The reason is that unlike single programs on single computers, distributed systems suffer from partial failures: one component dies, but the other components continue without knowing what exactly happened. This makes it nearly impossible to recover from failures in such a way that all components are guaranteed to have consistent states again. The idempotent way in which HTTP GET and PUT (and DELETE) are defined reduces this problem enormously: if a client suspects a problem with a request, it simply repeats it. It doesn’t need to find out the current resource state of the server, and it doesn’t need to correct it. On the other hand, a server simply responds to a request it receives from a client, and then forgets about this client. It doesn’t need to keep track of the client’s application state. Whether a client really receives a response message or has died, or whether the message was lost somewhere on the network, need not concern the server. This decoupling of the clients’ application states and the servers’ resource states is sometimes called statelessness. In practice, this means that almost anything can be a resource—except commands. For example, if you control a loudspeaker’s volume with an HTTP server, you can send it a PUT request with a representation of the desired state, e.g., . This is idempotent. You can send it as often as you want; seventy percent remains seventy percent. By contrast, commands are not always idempotent; e.g., would not be idempotent. Often, a URI name that contains a verb betrays such a mistake, e.g., . Multithreading Buffer An instance of class provides a threadsafe way of communication between actors (see Chapter 13). A buffer instance basically acts as a variable whose current value can be read and written: » This method puts into the buffer. The new value in the buffer replaces the old one. At most one value is buffered; there is no queuing of multiple values. The method performs the necessary locking to enable safe use of the buffer from multiple threads. Object may be . » This method gets the current buffer state, without changing it. The method performs the necessary locking to enable safe use of the buffer from multiple threads. The result may be . Index Symbols @ (at sign), preceding verbatim strings, 118 {} (curly braces). See initializers; lambda expressions => (lambda operator), 91 % (modulo operator), 54 A absolute URI, 31 actors, with multithreading, 129–131, 136 actuators, 1 drivers for, 165–167 hardware for, 145–146 server updating state of, 105–111, 118–119, 132–135 writing to, 11–14 AddressFamily class, 153 AnalogInput class, 154 analog input ports, reading from, 22–26 AnalogSensor class, 100, 102, 166–167 API key, for Pachube obtaining, 38 security of, 74 using, 49, 51, 65 Arduino-compatible shields, 146 assemblies (.dll files). See also specific assemblies list of, 153 .pe files translated from, 50 at sign (@), preceding verbatim strings, 118 B BlinkingLed program example, 11–14 boards, 146. See also Netduino Plus board braces ({}). See initializers; lambda expressions browser, as HTTP client, 30, 32, 35 Buffer class, 154, 168 buffer, for multithreading, 168 C cable modem, 44 cables Ethernet cable, ix, x micro USB cable, ix, x casting, 55, 110 C# language delegates, 101–102 initializers, 90–91 lambda expressions, 91–93 lock statement, 126–128 methods, defining, 4 modulo operator (%), 54 test client in, 111–114 type casts, 55, 110 using directive, 13, 63 while loop, 52 client. See HTTP client code examples. See program examples Concurrent Programming on Windows (Addison-Wesley), 136 Connect method, Socket class, 73, 82 contact information for this book, xi ContentLength property, HttpWebRequest class, 65 ContentType property, HttpWebRequest class, 65 control applications, 35 Cpu class, 153 Cpu.Pin type, 14 Create method, WebRequest class, 64 critical section, for locks, 126 CSharpRepresentation class, 154, 164 CSV representation for feed data, 40 for measured variables, 142 curly braces ({}). See initializers; lambda expressions D data streams, in feeds, 39–40 DateTime class, 153 deadlocks, in multithreading, 128–129 Debug class, 5, 153 debug output, 5–6, 8 delegates, 101–102 DELETE requests, 32 Deserializer delegate, 163 devices. See also hardware as HTTP clients. See HTTP client, device as as HTTP servers. See HTTP server, device as Device Solutions, 146 DHCP (Dynamic Host Configuration Protocol), 44, 44–45 DigitalActuator class, 108, 109, 154, 165–166 digital input ports, reading from, 17–19 DigitalSensor class, 154, 165, 165–166 Dispose methods, IDisposable interface, 63 DLL files. See assemblies (.dll files) Dns class, 73, 153 GetHostEntry() method, 73 DNS (domain name system), 45 DNS lookup, 73 domain name, Internet, 45 domain name system (DNS), 45 drivers for actuators and sensors, 165–167 for Netduino Plus board, 4 DSL modem, 44 Duffy, Joe (author) Concurrent Programming on Windows (Addison-Wesley), 136 E EfficientPutRequest program example, 71–75 embedded programming, v examples of. See program examples limited resources for, viii EMX Development System, 146 Encoding class, 153 errors. See exceptions; troubleshooting Ethernet cable, ix, x Ethernet router, ix examples. See program examples exceptions. See also troubleshooting Dispose methods still called after, 63 handling, 82 race conditions and, 124, 126 type casting errors causing, 110 F feeds. See also Pachube service accessing, 40–41 data format for, 40 data streams in, 39–40 ID for, 39, 49, 51 sending samples to, 51, 52, 55–56 setting up, 38–40 status of, 51 G general-purpose input/output (GPIO) pin, 11 GetBytes method, 63 GetChars method, 63 GetHandler delegate, 160–161 GET requests, 32, 67–69 for measured variable resources, 98, 99–103 resources not changed by, 103–104 GetRequestStream method, HttpWebRequest class, 65 GetResponse method, HttpWebRequest class, 65–66 GetResponseStream method, HttpWebResponse class, 66–67 GHI Electronics, 146 GPIO (general-purpose input/output) pin, 11 GPIO_PIN_A0 to _A5 constants, 14 GPIO_PIN_D0 to _D13 constants, 14 GPS devices, data from, 145 Gsiot.PachubeClient.dll file, 4, 49, 154 Gsiot.PachubeClient project, 49 Gsiot.Server.dll file, 4, 89, 154, 155–168 H HandleGet method, AnalogSensor class, 100 HandleRequest method, MeasuredVariable class, 100 hardware. See also specific components deploying projects to, 6–9 list of, ix–x, 145–148 HelloPachube program example, 43, 47–55, 48–55 HelloPachubeSockets program example, 77–82 HelloWebHtml program example, 93–94 HelloWeb program example, 85, 87–91 HelloWorld program example, 3, 4–5 host, in URI, 31 HTML (Hypertext Markup Language), 32 embedding JavaScript in, 114 HTTP responses formatted as, 93–94 measured variables formatted as, 142 HTTP client device as, 27, 34–35 examples using, 48–55, 77–82 when to use, 143–144 test client in C#, 111–114 in JavaScript, 114–118 web browser as, 30, 32, 35 HTTP headers, 56–57, 57–58 HTTP (Hypertext Transfer Protocol), 30 default port used by, 31, 95 reverse HTTP, 86–87 status code 200, 51, 57 HTTP requests, 32–34 classes and delegates for, 155–160 DELETE requests, 32 GET requests, 32, 67–69 for measured variable resources, 98, 99–103 resources not changed by, 103–104 handlers for, 92–93 POST requests, 32 PUT requests, 32–33, 55–56, 61–67 for manipulated variable resources, 106–107 resources changed by, 105, 118–120 with efficient use of memory, 71–75, 77–82 HTTP responses, 33, 66–69 in HTML, 93–94 lambda expression for, 91 from Pachube, 57–60 in ReceiveResponse example, 75–76 request handlers and, 92 HTTP server device as, 30 example of, 87–91 example of, with sensor, 97–104 examples of, with actuator, 105–111, 132 obstacles to, 83–84 relays for, 85–87 when to use, 143–144 Netduino Plus board as, 94–95 new implementation of, 143 test server, 149–152 HttpServer class, 154, 155–156 HttpWebRequest class, 64–66, 67–69, 153 HttpWebResponse class, 66, 67–69, 153 Hypertext Markup Language. See HTML Hypertext Transfer Protocol. See HTTP I idempotent, 104, 118–119 IDisposable interface, 63 if statement, 16 initializers, 90–91 InputPort class, 146, 153 input ports analog, reading from, 22–26 digital, reading from, 17–19 positive and negative logic for, 19 Internet addresses, 44–45, 73 reserved, 45 static, 83 Internet, connecting Netduino Plus board to, 43–47 Internet domain name, 45 Internet of Things, 29, 34 Internet resources. See websites int type, 55 IPAddress class, 153 IPEndPoint class, 153 IPHostEntry class, 153 J JavaScript embedding in HTML, 114 test client in, 114–118 verbatim strings, 118 JSON (JavaScript Object Notation) for feed data, 40, 41 for measured variables, 142 L lambda expressions, 91–93 LED as output port, 13–14 examples using, 11–14, 107–111, 132–135 LedController program example, 105–111 LightSwitch program example, 15–19 locks, in multithreading, 126–128 lock statement, 126–128 long type, 55 M MAC address, 46 Main() method, 4–5 Maker SHED website, ix MakerShield, 146 ManipulatedVariable class, 108, 110–111, 154, 162–163 manipulated variables, 106–107 MeasuredVariable class, 103–104, 154, 161–162 measured variables, 98–99 adding, 138–139 new representations for, 142–143 URI of, 138 measurements (samples) from sensors, 15 Method property, HttpWebRequest class, 65 methods. See also specific methods assigning to properties. See delegates defining, 4 MFDeploy tool network, configuring, 46–55 programs, erasing from Netduino Plus, 9 microcontrollers, 1 Microsoft.SPOT.Hardware.dll file, 153 Microsoft.SPOT.Native.dll file, 153 micro USB cable, ix, x modulo operator (%), 54 monitoring applications, 35 mscorlib.dll file, 153 multithreading, 121–131, 136 actors with, 129–131, 136 buffer for, 168 deadlocks in, 128–129 example using, 132–135 locks in, 126–128 race conditions in, 124–128 scheduler for, 121 shared variables in, 126, 136 N namespaces, 13, 153–154 NAT (network address translation), 45 Netduino Plus board, vi, ix analog inputs on, 22 connecting to Internet, 43–45 deploying programs to, 6–9 erasing programs from, 9 as HTTP server, 94–95 LED on, 11 MAC address for, 46 pins on, 13–14 resistor on, 18–19 SDK and drivers for, 4 test client for, in JavaScript, 114–118 NETMF 4.1 SDK, 4 NETMF board. See Netduino Plus board NETMF (.NET Micro Framework), v classes for, list of, 153–154 porting to different hardware, 147–148 properties for deployment, 7 setting up environment for, 3–4 .NET Micro Framework. See NETMF (.NET Micro Framework) network address translation (NAT), 45 NMEA protocol, 145 O ONBOARD_LED constant, 13, 14 ONBOARD_SW1 constant, 14, 17 online resources. See websites OutputPort class, 13, 146, 153 output ports, 13–14 Output window, 3, 8 P PachubeClient class, 154 Pachube service, 27, 37–41. See also feeds account for, setting up, 38 Internet address for, 45 secure sharing keys in, 38 ParallelBlinker program example, 132–135 parallel processing. See multithreading path, in URI, 31 .pe files, 50 pins assignments for, 13–14 changing assignments for a sensor, 138 Pins class, 154 Pins.GPIO_PIN_A0 to _A5 constants, 14 Pins.GPIO_PIN_D0 to _D13 constants, 14 Pins.ONBOARD_LED constant, 14 Pins.ONBOARD_SW1 constant, 14, 17 Port class, 153 port forwarding, 84, 95–96 ports, 94–96 reserved, 94 in URI, 31 POST requests, 31, 32 potentiometer, ix, 20, 21 examples using, 20–26, 48–55, 77–82, 99–103 reading from, 22–26 symbol for, in schematics, 23 as voltage divider, 25 Print method, Debug class, 5 process control, 98 processor boards, 146. See also Netduino Plus board program examples BlinkingLed, 11–14 EfficientPutRequest, 71–75 HelloPachube, 48–55 HelloPachubeSockets, 77–82 HelloWeb, 85 HelloWorld, 3, 4–5 LedController, 105–111 LightSwitch, 15–19 ParallelBlinker, 132–135 permission to use, xi ReceiveResponse, 75–76 requirements for, ix–x SimpleGetRequest, 67–69 SimplePutRequest, 61–63 TestServer, 149–152 VoltageMonitor, 97–104 VoltageReader, 20–26 programs building as solutions in Visual Studio, 5 creating as projects in Visual Studio, 5–6 deploying to device, 6–9 embedded, v, viii erasing from Netduino Plus, 9 running in debug mode, 8 projects. See programs ProtocolType class, 153 public keyword, for methods, 4 pull-down resistors, 19 pull-up resistors, 18, 19 PutHandler delegate, 161 PUT requests, 32–33, 55–56, 61–67 for manipulated variable resources, 106–107 resources changed by, 105, 118–120 with efficient use of memory, 71–75, 77–82 Q query, in URI, 31 R race conditions, in multithreading, 124–128 ReceiveResponse program example, 75–76 relative URI, 31 relays, 85–87, 95 representational state transfer. See REST representations classes and delegates for, 163–164 for feed data, 40, 41 for measured variables, 142 RequestHandler class, 157 RequestHandlerContext class, 154, 157–160 RequestRouting class, 156–157, 157 reserved addresses, 45 resistors, 17–19 potentiometer as type of, 23 symbol for, in schematics, 18 resources. See also manipulated variables; measured variables adding new type of, 141–142 classes and delegates for, 160–163 RESTful web services, 34, 119, 144 RESTful Web Services (O’Reilly), 34 REST (representational state transfer), 34 reverse HTTP, 86–87 Richardson, Leonard (author) RESTful Web Services (O’Reilly), 34 router, ix, 44 NAT performed by, 45 port forwarding on, 84, 96 Ruby, Sam (author) RESTful Web Services (O’Reilly), 34 S samples (measurements) from sensors, 15 sampling period, 15, 52–55, 53–55 scheduler, for multithreading, 121 scheme, in URI, 31 Secret Labs, Netduino Plus board. See Netduino Plus board SecretLabs.NETMF.Hardware.dll file, 154 SecretLabs.NETMF.Hardware.Netduino. dll file, 154 secure sharing keys, Pachube, 38 SendRequest method, 74–75 sensors, 1. See also monitoring applications adding new type of, 139–141 checking result of actuator request, 106–107 client accessing, 48–55, 77–82 drivers for, 165–167 hardware for, 145–146 measured variables from, 98–99 measurements (samples) from, 15, 51, 52, 55–56 pin assignment for, changing, 138 sampling period from, 15, 52–55, 53–55 server accessing, 97–104 switches as. See switches Serializer delegate, 163 server. See HTTP server shared variables, in multithreading, 126, 136 sharing keys, Pachube, 38 shields, 145–146 SimpleGetRequest program example, 67–69 SimplePutRequest program example, 61–63 Sleep method, Thread class, 12, 122 Smart Personal Object Technology (SPOT), 13 Socket API, 71, 77 Socket class, 73, 153 SocketException class, 153 SocketOptionLevel class, 153 SocketOptionName class, 153 SocketType class, 153 software requirements, 3–4 Solution Explorer adding references, 49 deployment properties, setting, 6–8 programs, creating, 6 solutions. See programs SparkFun website, ix SPOT (Smart Personal Object Technology), 13 static Internet address, 83 static keyword, for methods, 4 Stream class, 153 string conversion, 21 strings, verbatim, 118 switches positive and negative logic for, 19 state of, reading, 17–19 System.dll file, 153 System.Http assembly, 63, 64 System.Http.dll file, 153 System.IO namespace, 153 System namespace, 153 System.Net namespace, 153 System.Net.Sockets namespace, 153 T TCP/IP protocol, 81 test client in C#, 111–114 in JavaScript, 114–118 test server, 149–152 Thread class, 12, 122, 153 threads. See multithreading TimeSpan class, 153 Topaz i.MX25 board, 146 ToString method, 21 troubleshooting. See also exceptions deployment problems, 9 failed connection, 82 HelloPachube program, 51 test server failing, 152 type casts, 55, 110 U Uniform Resource Locator. See URI (Uniform Resource Identifier) URI (Uniform Resource Identifier), 31–32 for accessing Pachube feeds, 40–41 constructing for HTTP request, 74 of manipulated variable, 106 of measured variable, 98–99, 138 using directive, 13, 63 V variable declarations, 12 variables, manipulated, 106–107 variables, measured, 98–99 adding, 138–139 new representations for, 142–143 URI of, 138 variables, shared, 126, 136 var keyword, 12 verbatim strings, 118 Visual Studio Express 2010, ix, 3 projects, creating, 5–6 solutions, building, 6 void keyword, for methods, 4 voltage divider, 25 VoltageMonitor program example, 97–104 VoltageReader program example, 20–26 voltage sensor. See potentiometer W WaitUntilNextPeriod method, 53–55 web browser, as HTTP client, 30, 32, 35 web interaction patterns, 34–35 Web of Things, 34 WebRequest class, 64, 65, 153 web server. See HTTP server websites for this book, xi GHI Electronics online community, 145 Gsiot libraries, 4 Gsiot.PachubeClient project, 49 hardware components, ix–x Netduino Plus board, vi Netduino Plus online community, 145 Netduino Plus schematics and layout, 148 Netduino Plus SDK and drivers for, 4 NETMF, v, 145 NETMF 4.1 SDK, 4 Pachube service, 38 processor boards, 146 shields, 145, 146 Visual Studio Express 2010, 4 while loop, 52 Windows operating system, ix, 4 Write method, OutputPort class, 13 X XMLHttpRequest class, 115 XML representation, 32 for feed data, 40 for measured variables, 142 Y Yaler, reverse HTTP relay, 87 About the Author Dr. Cuno Pfister studied computer science at the Swiss Federal Institute of Technology in Zürich (ETH Zürich). His PhD thesis supervisor was Prof. Niklaus Wirth, the designer of the Pascal, Modula-2, and Oberon programming languages. Dr. Pfister is the Managing Director of Oberon microsystems, Inc., which has worked on various projects related to the Internet of Things, from mobile solutions to a large hydropower-plant monitoring system with 10,000 sensors. Colophon The cover, heading, and body font is BentonSans, and the code font is Bitstreams Vera Sans Mono. Want to read more? You can find this book at oreilly.com in print or ebook format. It’s also available at your favorite book retailer, including Amazon and Barnes & Noble. Spreading the knowledge of innovators oreilly.com