Medium 9781449393571

Getting Started with the Internet of Things: Connecting Sensors and Microcontrollers to the Cloud

Views: 1636
Ratings: (0)

What is the Internet of Things? It's billions of embedded computers, sensors, and actuators all connected online. If you have basic programming skills, you can use these powerful little devices to create a variety of useful systems—such as a device that waters plants when the soil becomes dry. This hands-on guide shows you how to start building your own fun and fascinating projects.

Learn to program embedded devices using the .NET Micro Framework and the Netduino Plus board. Then connect your devices to the Internet with Pachube, a cloud platform for sharing real-time sensor data. All you need is a Netduino Plus, a USB cable, a couple of sensors, an Ethernet connection to the Internet—and your imagination.

  • Develop programs with simple outputs (actuators) and inputs (sensors)
  • Learn about the Internet of Things and the Web of Things
  • Build client programs that push sensor readings from a device to a web service
  • Create server programs that allow you to control a device over the Web
  • Get the .NET classes and methods needed to implement all of the book's examples

List price: $19.99

Your Price: $15.99

You Save: 20%

 

17 Slices

Format Buy Remix

1. Hello World

ePub

To familiarize you with the development environment, your first program should be a simple HelloWorld. Because the Netduino Plus board does not have a display, use the USB connection between board and development PC to write the string Hello World to the development environments Output window running on the PC, as illustrated in Figure1-1. The USB connection is used to deploy and debug your programs, and in the HelloWorld example, it allows you to send the Hello World string to your development PC.

Figure1-1.Architecture of HelloWorld example

Before writing your first program for the .NET Micro Framework, you need to install a few tools and libraries, including:

Microsoft Visual Studio 2010 or later. The free Visual Studio Express version is sufficient. Full commercial versions can also be used, of course. For my descriptions and screenshots, I will use Visual Studio Express. If you use Visual Studio Express, you must install the C# edition from http://www.microsoft.com/express/Downloads.

 

2. Writing to Actuators

ePub

You can now write your first truly embedded program. In a time-honored tradition, this program, BlinkingLed, which is the embedded equivalent of HelloWorld, makes an LED blink.

In Figure2-1, the large box indicates a Netduino Plus, which has a blue LEDlabeled LED on the boardthat can be controlled from an application program. This LED is connected to a general-purpose input/output (GPIO) pin of the microcontroller. Most microcontrollers have a number of such GPIO pins, each of which can be configured as digital input or digital output. A digital output might be connected to an LED, as in our example; a digital input might be connected to a switch or button.

Figure2-1.Architecture of BlinkingLed

The BlinkingLed program, shown in Example2-1, contains a simple endless loop that switches the LED on, waits for half a second, switches the LED off again, waits for another half a second, and then starts all over.

Example2-1.BlinkingLed

The calls to the Sleep method in the Thread class make the program pause for (at least) a given number of milliseconds (a millisecond is 1/1000th of a second). In the .NET Micro Framework, using Thread.Sleep is the best practice for waiting, as it allows the hardware to go into a lower-power state to conserve energy.

 

3. Reading from Sensors

ePub

The first example in this chapter, LightSwitch, not only writes to output ports, it also reads from input ports. The switch input is used to control the LED output, as shown in Figure3-1. While the switch (actually a push button on the Netduino Plus board) is closed, the LED stays lit; otherwise, it is dark.

Figure3-1.Architecture of LightSwitch

The program Example3-1 reads the current switch state periodically and copies it to the LED. This is done frequently enough that a user does not detect a delay when she opens or closes the switch. Delays of 1/10th of a second or less are undetectable by humans; therefore, the loop is executed every 100 milliseconds.

A value read from a sensorin this case, the switch or buttonis called a measurement or sample. The time span between two subsequent measurements is called the sampling period.

Example3-1.LightSwitch

Since the first branch of the if (isClosed) statement is executed if isClosed is true, and the other branch is executed if isClosed is false, the entire if statement can be completely replaced by the following statement:

 

4. The Internet of Things

ePub

Now that you have seen how to work with simple sensors and actuators, it is time to take the next step toward an Internet of Things application. In this chapter, I will briefly introduce the Internet of Things, and the related Web of Things.

The Internet of Things is a global network of computers, sensors, and actuators connected through Internet protocols.

A most basic example is a PC that communicates over the Internet with a small device, where the device has a sensor attached (e.g., a temperature sensor), as shown in Figure4-1.

Figure4-1.A PC and a device connected through the Internet

The TCP/IP protocol is the key Internet protocol for such communication scenarios. It enables the transfer of byte streams between two computers in either direction. For example, using the TCP/IP protocol, the device in Figure4-1 may periodically deliver temperature measurements to a program running on the PC.

While it is possible to run any kind of proprietary protocol on top of TCP/IP, there are a few popular and widely supported standard protocols. If you use a standard protocol to deliver your sensor data, youll be able to work with many more devices and applications than if you developed your own proprietary protocol.

 

5. Pachube

ePub

Imagine that your Netduino Plus uses a sensor to take measurements periodically. After each measurement, the Netduino Plus immediately sends the sample to a server for storage and later retrieval. This server effectively provides a feed resource to which you publish your data samples. You may already know the concept of feeds from RSS feed readers. A feed entry can be anything of interest, from political news to blog entries to measurements, as in the case of your Netduino Plus. In a way, a feed that contains measurements can be thought of as a news source about the physical world.

For such an example, you need a suitable web service to which your device can send its measurements. Conveniently, theres a free service, Pachube, which does exactly this. It provides web-based interfaces for storing and for accessing feeds, as shown in Figure5-1.

Figure5-1.Example of a Pachube feed

The example in Figure5-1 is a NASA feed. It is atypical insofar as the source of its data is a multimillion dollar space probenot exactly a low-cost device. Nevertheless, you can use Pachube just as well with your $60 Netduino Plus.

 

6. Hello Pachube

ePub

In this chapter, I will show a basic HTTP client, HelloPachube, that pushes samples to Pachube, as shown in Figure6-1.

Figure6-1.Architecture of HelloPachube

HelloPachube runs on the Netduino Plus and sends measurements to the Pachube web service by issuing HTTP PUT requests. The user, through his web browser, sends HTTP GET requests to Pachube to retrieve feed entries. The data flow originates in the device, goes up to Pachube, and continues from there to the user.

Before you can run such a client, you need to make sure that your Netduino Plus board has access to the Interneti.e., it can send request messages to any server visible on the Internet. I assume that your Netduino Plus is connected to the Internet via a router and a cable or DSL modem (Figure6-2).[2] This means that you have a local area network to which both the board and your development PC are connected. During development and debugging, the PC and Netduino Plus are directly connected via a USB cable as well.

Figure6-2.Connection of board to the Internet

 

7. Sending HTTP Requests—The Simple Way

ePub

HelloPachube in Chapter6 is so simple because the Gsiot.PachubeClient library is built for the single purpose of pushing samples to Pachube. It completely hides the .NET classes needed to implement an HTTP client. If you want to use Pachube in a different way, or if you want to write clients for other services, you can use the more general HttpWebRequest and HttpWebResponse classes, which are located in the System.Net namespace.

Example7-1 shows how these classes can be used to send a single sample to Pachube.

Example7-1.SimplePutRequest

To run this example:

Make sure your Netduino Plus is connected to your Ethernet router, and that it is correctly configured for network access (see Chapter6).

Create a new Visual Studio project (using the Netduino Plus template) and name it SimplePutRequest. Replace the contents of Program.cs with the code from Example7-1.

You must replace the strings for apiKey and feedId so that they match your Pachube API key and feed ID.

Right-click on References in the Solution Explorer. Select AddNew Reference. In the Add Reference dialog box, click on the .NET tab (if it is not already selected). Locate System.Http in the list and click OK to add this assembly to your project.

 

8. Sending HTTP Requests—The Efficient Way

ePub

While the HttpWebRequest and HttpWebResponse classes are relatively convenient to use, they gobble up a large part of the available Flash and RAM on a Netduino Plus. Because they are built on top of the so-called Socket API, it can make sense to use the Socket API directly instead. This is more work, but it can reduce the memory footprint of an application considerably.

Moreover, the main message of this book is that HTTP is not black magic and requires neither high-powered computers nor huge, complex web frameworks. Using the Socket API makes that obvious, because you see much more of what really goes on than if you use only higher-level APIs. For this reason, I will show an alternative to SimplePutRequest called EfficientPutRequestwhich is efficient mainly in the sense that it has a small memory footprint.

To send a sample to Pachube, you can use the code in Example8-1.

Example8-1.EfficientPutRequest

This example starts in the same way as SimplePutRequest (Example7-1) from Chapter7with the two constants apiKey and feedId, which you must set to your API key and feed ID. Next, it opens a connection using the helper method Connect, and then it uses the helper method SendRequest to create the HTTP message and send it over the connection.

 

9. Hello Pachube (Sockets Version)

ePub

In this chapter, I will present a version of a complete Pachube client that uses the Socket API. It demonstrates that this low-level API is a viable alternative, especially for fire and forget requests.

HelloPachubeSockets (Example9-1) performs some initializations in its Main method, enters an endless loop in which it waits until it is time for the next measurement, performs the measurement, and then sends the result to Pachube. This is repeated every 20 seconds like in the original HelloPachube program.

Example9-1.HelloPachubeSockets

To run the program:

Create a new Visual Studio project (using the Netduino Plus template) and name it HelloPachubeSockets. Replace the contents of Program.cs with the code from Example9-1.

Replace the strings for apiKey and feedId so they match your Pachube API key and feed ID.

Next, build the project and deploy it to your Netduino Plus, as described in the section Deploying to the Device in Chapter1.

When the Pachube client is started, something like the following output will be shown:

 

10. Hello Web

ePub

On the Web, the equivalent to HelloWorld is a server program that handles GET requests from web browsers and returns a message to them, as shown in Figure10-1.

Figure10-1.Architecture of HelloWeb

Isnt there supposed to be a problem with making a device a web server, as mentioned in PartIII? How can we sidestep the problems caused by firewalls, network address translations, and the shortage of IPv4 Internet addresses?

The HelloWeb program works thanks to a relay between the Netduino Plus and the client who wants to connect to it over the Internet. The client sends its request not directly to the device, but instead to this relay; from there, the request is forwarded to the device. The response comes back the same way, indirectly, via the relay (see Figure10-2).

Figure10-2.Relay between client and device (application view)

You may wonder how that setup solves any problem. After all, the device (your Netduino Plus) is still buried behind a NAT and firewall, and it therefore has no unique public Internet address to which requests could be sent. A client can obviously send requests to the relay, but how can the relay forward it to the device if the device cannot even be addressed?

 

11. Handling Sensor Requests

ePub

Chapter10 is an example of an HTTP server, but it doesnt use any sensors or actuators. In this chapter, Ill show how you can add sensor access to your server programs (Figure11-1).

Figure11-1.Architecture of VoltageMonitor

VoltageMonitor, which youll see later in Example11-1, shows how to handle GET requests to a sensor resource, more specifically one that represents some voltagee.g., a voltage produced by an attached potentiometer, photo resistor, or similar sensor. You can use any web browser as a client to inspect the current voltage. After all, a web browser is basically an engine for initiating GET requestsand for displaying the responses, of course.

An HTTP server manages resources. In this example, a resource is provided that has the meaning, actual voltage value, as measured by a sensor attached to the board. A resource that contains an actual value is called a measured variable. A measured variable changes its value over time, depending on a physical process: when the user physically turns the potentiometers knob, the measured variable changes its value accordingly. This means that subsequent GET requests to the same resource may yield different responses.

 

12. Handling Actuator Requests

ePub

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 chapters example, an LEDs state (on/off) is controlled through a web service, as illustrated in Figure12-1.

Figure12-1.Architecture of LedController

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.

If you dont 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 utilitywhich is usually installed by default on Mac OS X and Linuxyou could use a command like this to turn the LED on (be sure to change the URI to match your configuration):

 

13. Going Parallel

ePub

Imagine that you have written a program that controls some physical process, like rapidly blinking an LED at a fixed frequency. You want to control the parameters of this process through a web service interface, perhaps to adjust the blinking period. This simple scenario raises a far-reaching question. Consider our previous server examples that repeatedly wait for new incoming HTTP requests. Whenever a request arrives, the server wakes up, does something, sends back a response, and then waits again. While it waits, the server blocks all other activity until the next request comes in, which may easily take hours. This means that even if you wrote some code to blink the LED, its not going to blink if the server is sitting around waiting. This is not what you want, of course.

To solve this problem, the .NET Micro Framework provides a very powerful mechanism called multithreading. Multithreading is a mechanism for splitting up a program into several parallel activities called threads. Each thread provides a single stream of execution, yet they all share the same resources (i.e., they can access the same C# objects). Each of the examples so far used only one thread, which is started implicitly along with the application. Additional threads can be started explicitly, as I will show soon. The point is that while a thread may be waiting due to some blocking call, the others are free to continue (unless they have run into blocking calls themselves).

 

14. Where Can I Go from Here?

ePub

The title of this book is Getting Started with the Internet of Things, and I hope that it did help you take the first steps. You may now be wondering where to go next. In this chapter, I compiled some things that might be of interest to you.

Now that you have seen several example servers for monitoring sensors and for controlling actuators, its possible to make various changes to such a server (illustrated in Figure14-1). I mainly discuss sensors and measured variables, but actuators and manipulated variables can be handled in the same way (if not stated otherwise).

Figure14-1.Various ways to change a server

If you have moved a physical sensor from one pin to another, go to the corresponding sensor object and change the pin. For example, if you want to move the potentiometer of Example11-1, one pin position to the right, change the InputPin property of voltageSensor from Pins.GPIO_PIN_A1 to Pins.GPIO_PIN_A2. (And for this example, dont forget to move highPort and lowPort as well, or use other ways to provide power and ground to the potentiometer.) The pins of the Netduino Plus that are accessible through connectors are listed in Table2-1 in Chapter2.

 

A. Test Server

ePub

For testing applications that send or receive HTTP messages, i.e., HTTP clients, you can use suitable tools for logging HTTP traffic, such as Wireshark (http://www.wireshark.org/) or Fiddler (http://www.fiddler2.com/). However, before issuing HTTP requests to a real web service out in the wild, you may want to know beforehand exactly what you would send. A simple test server is often all that you need. You run your client program (e.g., Example7-1), on your Netduino Plus, and you run a .NET test server that logs an incoming request on your development PC.

In your client program for the Netduino Plus, change the request URI to something like this:

but replace 192.168.5.100 with the Internet address of your PC. You can find this address by following these steps on Windows:

Start the command prompt application at StartAll ProgramsAccessoriesCommand Prompt.

Type in the string ipconfig, and then press Enter.

In the resulting output, your PCs Internet address is called IP Address.

To view the IP address on the Mac, open System Preferences, click Network, and select an active (green) network adapter. On Linux, you can open a Terminal and use the ipconfig command to view IP addresses for your network adapters.

 

B. .NET Classes Used in the Examples

ePub

The following tables list the classes used in the NETMF examples, with their respective namespaces and assemblies.

TableB-1 gives the classes Microsoft created for .NET or the .NET Micro Framework.

TableB-1..NET Micro Framework classes

Class

Namespace

Assembly

AddressFamily

System.Net.Sockets

System.dll

Cpu

Microsoft.SPOT.Hardware

Microsoft.SPOT.Hardware.dll

DateTime

System

mscorlib.dll

Debug

Microsoft.SPOT

Microsoft.SPOT.Native.dll

Dns

System.Net

System.dll

Encoding

System.Text

System.dll

HttpWebRequest

System.Net

System.Http.dll

HttpWebResponse

System.Net

System.Http.dll

InputPort

Microsoft.SPOT.Hardware

Microsoft.SPOT.Hardware.dll

IPAddress

System.Net

System.dll

IPEndPoint

System.Net

System.dll

IPHostEntry

System.Net

System.dll

OutputPort

Microsoft.SPOT.Hardware

Microsoft.SPOT.Hardware.dll

Port

Microsoft.SPOT.Hardware

Microsoft.SPOT.Hardware.dll

ProtocolType

System.Net.Sockets

System.dll

Socket

System.Net.Sockets

System.dll

SocketException

System.Net.Sockets

System.dll

SocketOptionLevel

System.Net.Sockets

System.dll

SocketOptionName

System.Net.Sockets

 

HTTP Server

ePub

Here is a summary of the Gsiot.Server library interface. All items described below can be found in namespace Gsiot.Server, which is implemented in Gsiot.Server.dll.

An instance of class HttpServer represents a web service that handles HTTP requests at a particular port, or uses a relay server to make the service accessible even without a public Internet address:

int Port

Optional property that is set to 80 by default. If the server does not use a relay (see RelayDomain), this property indicates the port for which the server handles incoming HTTP requests.

string RelayHost

Optional property, which is set to try.yaler.net by default. If the server uses a relay, this property indicates the address of the relay. If the server does not use a relay (see RelayDomain below), this property is ignored.

string RelayDomain

Optional property, which determines whether a relay is used, and if one is used, what domain name is registered at the relay. By default, it is null, i.e., no relay is used.

string RelaySecretKey

 

Details

Print Book
E-Books
Slices

Format name
ePub
Encrypted
No
Sku
9781449310110
Isbn
9781449310110
File size
0 Bytes
Printing
Not Allowed
Copying
Not Allowed
Read aloud
No
Format name
ePub
Encrypted
No
Printing
Allowed
Copying
Allowed
Read aloud
Allowed
Sku
In metadata
Isbn
In metadata
File size
In metadata