Chapter 16. The Internet of Things

In general, the primary way people interact with the Internet is by using a browser to view web pages. The Internet of Things, or IoT, is the concept that other “things” can also have a presence on the Internet. For example, smart appliances for home automation are connected to the Internet and can provide useful information to homeowners and utility companies. In addition, users of wearable devices (such as smart watches and fitness trackers) might consider themselves to be part of the IoT, as personal information about their location and heart rate finds its way onto cloud services on the Internet. 

Controlling electronic devices takes on a whole new dimension if that control is over the Internet. In this chapter, you will learn how to take control of the actuators described in the book using a web interface.

In practical terms, there are two main ways of making your Raspberry Pi network and therefore Internet capable.

One is the direct approach to have the Raspberry Pi act as a web server. It can then serve up a web interface that you can connect to from any browser and interact with. So, for example, you press a button on the web page served from the Raspberry Pi and a GPIO output turns on. We will use this approach in “Project: A Raspberry Pi Web Switch”.

The second approach is for the Raspberry Pi to communicate with a cloud service that acts as a broker for messages to pass between devices and people on the Internet. For example, in “Project: Puppet Twitter Notifier”, the IFTTT (If This Then That) cloud service will monitor your Twitter account and make Pepe the Puppet dance every time someone tweets with the hashtag #dancepepe. 

If you don’t want to use Twitter, you can instead use email, Facebook updates, or pretty much any kind of trigger that the If This Then That service can use.

Raspberry Pi and Bottle

Bottle is a very lightweight and easy-to-use web server framework written entirely in Python. It’s a great way of creating simple web server applications for a Raspberry Pi.

To install Bottle, enter the following commands:

$ sudo apt-get update
$ sudo apt-get install python-bottle

The next step is to create a Python program that uses Bottle to create a minimal web server that you can connect to from a browser anywhere on your network. Enter the following command to create a new Python file:

$ nano test_bottle.py

 Then add the following text to the file:

from bottle import route, run

@route('/')
def index():
    return '<h1>Hello World</h1>'

run(host='0.0.0.0', port=80)

The @route marker before the index function indicates that index is responsible for generating the HTML to be sent back to any browser that hits the root of the web server (the website itself rather than a particular page). In this case, it will just return the text “Hello World” formatted as a first-level heading. To check that the program works, run the following command:

$ sudo python test_bottle.py 
Bottle server starting up (using WSGIRefServer())...
Listening on http://0.0.0.0:80/
Hit Ctrl-C to quit.

Then open a browser, either on the Raspberry Pi itself or on any computer in your network, and use the IP address of your Raspberry Pi as the URL (Figure 16-1). To find the IP address of your Raspberry Pi see “Finding the IP Address of a Raspberry Pi”.

Figure 16-1. “Hello World” in Bottle

Project: A Raspberry Pi Web Switch

Because a Bottle web server is just a Python program, it can do more than just serve up HTML for a browser. It can also use the RPi.GPIO library to control the GPIO pins in response to hyperlinks or buttons being clicked on a web interface that it serves up to a browser (Figure 16-2).

You can use this device to turn AC appliances on and off if you use a PowerSwitch Tail, as described in  “Project: Raspberry Pi Timer Switch” in Chapter 13.

Figure 16-2. A web interface for the Internet switch project

Hardware

This project provides a web interface that will set GPIO pin 18 high or low from a browser. What you choose to connect to pin 18 is entirely up to you. You may decide to keep it simple and just use an LED. If so, build the hardware for “Experiment: Controlling an LED”. Or, you might have it control a PowerSwitch Tail and some AC appliance, as described in “Project: Raspberry Pi Timer Switch”.

Software

Bottle provides a neat way of keeping the HTML to be served to a browser separate from the Python program logic that controls the whole thing. The mechanism is called templating. This project uses just two files, which you can find in projects/pr_web_switch/.

The file home.tpl contains the HTML for the web interface:

<html>
<body>

<h1>Web Switch</h1>

<a href="/on">ON</a>

<a href="/off">OFF</a>

</body>
</html>

This HTML when viewed in a browser looks like Figure 16-2. The key lines are the two hyperlink a tags. The href attribute of the a tags specify the web address to go to if ON or OFF are clicked. If you are familiar with HTML and CSS styles, you may like to smarten up these hyperlinks and make them look a bit more like real buttons.

In the case of the ON hyperlink, a web request will be sent to the IP address of your Raspberry Pi with /on on the end of it. This is then handled in the Python code that will be discussed next:

from bottle import route, run, template, request
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)  1
CONTROL_PIN = 18
GPIO.setup(CONTROL_PIN, GPIO.OUT)

@route('/')    2
def index():
    return template('home.tpl')
    
@route('/on')  3
def index():
    GPIO.output(CONTROL_PIN, 1)
    return template('home.tpl')
    
@route('/off')  4
def index():
    GPIO.output(CONTROL_PIN, 0)
    return template('home.tpl')    
        

try: 
    run(host='0.0.0.0', port=80)   5
finally:  
    print('Cleaning up GPIO')
    GPIO.cleanup()
1

Set up pin 18 as the output control pin.

2

If a browser visits the root of this web server, just return the contents of the home.tpl template.

3

This is the handler if the URL path has on on the end of it (in which case, the control pin is set high before returning the home template again).

4

The handler for the OFF hyperlink.

5

Start the web server running on port 80 (the default port for web pages).

Using the Web Switch

To start the web server running, use this command:

$ sudo python web_switch.py

Then open a browser tab on the IP address for your Raspberry Pi, which should then display as Figure 16-2.

Try clicking the ON and OFF hyperlinks and whatever you have attached to GPIO 18 should turn on and off.

Arduino and Networks

With its built-in network interface and availability of low-cost USB WiFi modules, the Raspberry Pi is actually far more suited to IoT projects than an Arduino Uno. 

You can buy add-on WiFi shields for the Arduino, but they are expensive. Other models of Arduino like the Arduino Yun include WiFi but are also somewhat expensive and not terribly easy to use.

If you want to use an Arduino-like WiFi device in IoT projects, then I recommend that you use something like the Photon board from Particle.io (Figure 16-3).

Figure 16-3. The Photon

The Photon was styled on a version of the Arduino called the Arduino Nano but has a built-in WiFi module. The device is a true cloud-based device in that you communicate with it and install software on it all over the Internet. This means that you can embed your Photon in a project and still program it without having to have physical access to it. It just needs to be powered up and connected to your WiFi network.

The programming language for the Photon is also based on Arduino C, but instead of the standard Arduino IDE, it is programmed from a web-based IDE. You can find out more about using the Photon at particle.io and also from my book Make: Getting Started with the Photon.

Another useful Arduino-ish device that also gets used in IoT projects is the ESP8266. These devices (Figure 16-4) are fantastically low cost and can be set up to program from the Arduino IDE as if they were an Arduino, or they can be connected to an Arduino to provide it with a low-cost WiFi connection.

Figure 16-4. An ESP8266 module

Using this device is gradually getting simpler, but (at the time of writing) it still requires a lot of configuration to properly set up. If you want to learn more about this device, then search the Internet for ESP8266 and try one of the many getting started tutorials that you will find there, such as http://makezine.com/2015/04/01/esp8266-5-microcontroller-wi-fi-now-arduino-compatible/.

Project: Puppet Twitter Notifier

Let’s build on “Project: Pepe the Puppet Gets a Voice” to make Pepe respond to tweets containing the hashtag #dancepepe, causing Pepe to do his little dance and play a sound. The project can use the exact same hardware as “Project: Pepe the Puppet Gets a Voice”, but with the PIR sensor removed. Only the software will change. Figure 16-5 shows the build from “Project: Pepe the Puppet Gets a Voice” but with the PIR sensor removed.

Figure 16-5. Pepe the Puppet wired up to respond to Twitter

Putting Pepe on the Internet

Making Pepe respond to tweets is a two-stage process. The first stage is to allow Pepe to respond to web requests so that you can trigger his dancing from a web browser. The second step will use the IFTTT (If This Then That) web service to monitor Twitter for the #dancepepe hashtag and then cause a web request to be sent, to link up with the first stage.

You will use the dweet.io web service to get Pepe responding to web events. This service is free (subject to a reasonable limit on the number of messages you can send a month) and describes itself as Twitter for the IoT. It does not require a login and is very easy to use. It also has a Python library that will make integrating it with Pepe’s software straightforward.

To install dweepy, the Python library for dweet.io, run the following commands:

$ git clone git://github.com/paddycarey/dweepy.git
$ cd dweepy
$ sudo python setup.py install

There is a slight problem using this library with Python 2 and SSL that is easily solved by using the following commands to change the version of HTTP requests that Python 2 uses:

$ sudo apt-get install python-pip
$ sudo pip install requests==2.5.3

You should now be able to run the program for this project (puppet_web.py), which you will find in python/projects/puppet_web, using this command:

$ sudo python puppet_web.py

You can test out the progress of the project with a web browser. Just navigate to the URL https://dweet.io/dweet/for/pepe_the_puppet (Figure 16-6).

Figure 16-6. Controlling the puppet from a web browser

As soon as you go to that URL, Pepe should start doing his stuff.

Much of the program is the same as “Project: Pepe the Puppet Gets a Voice” so you may wish to refer back to that project for the main body of the code:

from Adafruit_PWM_Servo_Driver import PWM  
from pygame import mixer
import time
import dweepy  1

pwm = PWM(0x40)
mixer.init()   
mixer.music.load("pepe_1.wav")

dweet_key = 'pepe_the_puppet'   2

servoMin = 150  # Min pulse length out of 4096     
servoMax = 600  # Max pulse length out of 4096

dance = [     
  #lh  lf  rf  rh
  [130, 20, 20, 130],
  [30, 160, 160, 30],    
  [90, 90, 90, 90]
]

delay = 0.2   
  
def map(value, from_low, from_high, to_low, to_high):  
  from_range = from_high - from_low
  to_range = to_high - to_low
  scale_factor = float(from_range) / float(to_range)
  return to_low + (value / scale_factor)
  
  
def set_angle(channel, angle):  
  pulse = int(map(angle, 0, 180, servoMin, servoMax))
  pwm.setPWM(channel, 0, pulse)
  
def dance_step(step):  
  set_angle(0, step[0])
  set_angle(1, step[1])
  set_angle(2, step[2])
  set_angle(3, step[3])
  
def dance_pupet():    
    for i in range(1, 10):
        for step in dance:
            dance_step(step)
            time.sleep(delay)
    
pwm.setPWMFreq(60)   

      
while True:
    try:    3
        for dweet in dweepy.listen_for_dweets_from(dweet_key):   # 4
            print("Dance Pepe! Dance!")
            mixer.music.play()
            dance_pupet()
    except Exception:
        pass
1

Import the dweepy library.

2

dweet uses this value as a key for dweets that are of interest you. If you leave they key like this, then other readers of this book who are working on this project will be able to trigger your puppet (and vice versa), which is kind of fun. If you want to make things more private, just choose a different value for this key.

3

The code inside the main loop is all contained in a try/except error handler, because the web connection that the program listens on times out after a while, causing an exception. The try/except code masks this and allows the program to try again after such errors.

4

dweet.io allows you to wait and listen for new dweets for your key and perform an action when they arrive.

IFTTT (If This Then That)

IFTTT is a web service that allows you to set up triggers that cause an action. For example, you could create an IFTTT recipe that sends you an email (the action) whenever someone mentions you on Twitter (the trigger). 

In this project, IFTTT will be used to monitor Twitter for mentions of the hashtag #dancepepe and then send the web request to get Pepe dancing and playing his sound clip.

Here are the steps involved in setting up IFTTT to do this job.

Step 1: Create a new recipe

Sign up to use the IFTTT service (it’s free). Then click the Create Recipe button. You will then see the page shown in Figure 16-7.

Figure 16-7. Creating a new recipe in IFTTT

Step 2: Define the trigger

Click the big “this” hyperlink and then find the Twitter channel from the list of channels. Within the Twitter channel, find the trigger “New tweet from search” and then enter “#dancepepe” in the “Search for” field (Figure 16-8).

Figure 16-8. Setting the Twitter trigger

Step 3: Add the web request action

Once the trigger has been defined, the “if this then that” screen should reappear and now it’s time to define the action by clicking the “that” hyperlink and then searching for the “Maker” action channel. Select the only action available (“Make a web request”) and then complete the form shown in Figure 16-9.

Figure 16-9. Completing the action form

Step 4: Finish the recipe

Click the Create Action button and then confirm the completion of the recipe by clicking Create Recipe (Figure 16-10).

Figure 16-10. Completing the recipe

Once complete, the recipe will automatically go live.  You may find that IFTTT asks you to log in to the Twitter Channel at some point in this process.

Using the Project

That’s it, the project is ready to go. You can test it out by tweeting the hashtag #dancepepe. It may take a little while for IFTTT to find the tweet, so don’t worry if nothing happens for a minute or two. 

If, after a minute or two, nothing happens, you can check the IFTTT log for your recipe, which is the icon that looks like a list of bullet points on the page for the recipe. This will show you if the recipe was triggered (as well as any errors).

If you want to record your own message for Pepe to play, see “Arduino Experimentation”.

You should also explore the additional triggers available on IFTTT, as there is no end of interesting things that could set Pepe off!

Summary

In this chapter, you have learned how to run a web server on a Raspberry Pi and also make use of web services such as IFTTT and dweepy to make fun IoT projects.

I hope this book has served to provide you with some useful nuggets of information and some ideas for great projects that you can start making.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset