Chapter 16. The Internet of Things

16.0 Introduction

The Internet of Things (IoT) is the rapidly growing network of devices (things) connected to the internet. That doesn’t just mean more and more computers using browsers, but actual appliances and wearable and portable technology. This includes all sorts of home automation, from smart appliances and lighting to security systems and even internet-operated pet feeders, as well as lots of less practical but fun projects.

In this chapter, you learn how your Raspberry Pi can participate in the IoT in various ways.

16.1 Controlling GPIO Outputs Using a Web Interface

Problem

You want to control general-purpose input/output (GPIO) outputs using a web interface to your Raspberry Pi.

Solution

Use the bottle Python web server library (Recipe 7.17) to create an HTML web interface to control the GPIO port.

To make this recipe, you will need the following:

Figure 16-1 shows the breadboard layout for this.

F1400
Figure 16-1. The breadboard layout controlling GPIO outputs from a web page

An alternative to using a breadboard is to attach a Raspberry Squid and Squid Button (see Recipe 9.10 and Recipe 9.11). You can plug these directly into the GPIO pins of the Raspberry Pi, as shown in Figure 16-2.

F1401
Figure 16-2. Raspberry Squid and Squid Button

To install the bottle library, see Recipe 7.17.

Open an editor and paste in the following code (ch_16_web_control.py):

from bottle import route, run
from gpiozero import LED, Button

leds = [LED(18), LED(23), LED(24)]
switch = Button(25)

def switch_status():
    if switch.is_pressed:
        return 'Down'
    else:
        return 'Up'

def html_for_led(led_number):
    i = str(led_number)
    result = " <input type='button' 
         onClick='changed(" + i + ")' value='LED " + i 
         + "'/>"
    return result

@route('/')
@route('/<led_number>')
def index(led_number="n"):
    if led_number != "n":
        leds[int(led_number)].toggle()
    response = "<script>"
    response += "function changed(led)"
    response += "{"
    response += "  window.location.href='/' + led"
    response += "}"
    response += "</script>"
    
    response += '<h1>GPIO Control</h1>'
    response += '<h2>Button=' + switch_status() + '</h2>'
    response += '<h2>LEDs</h2>'
    response += html_for_led(0) 
    response += html_for_led(1) 
    response += html_for_led(2) 
    return response

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

As with all the program examples in this book, you can also download this program (see Recipe 3.22).

You must run the program as a superuser, using Python 2:

$ sudo python ch_13_web_control.py

If it starts correctly, you should see a message like this:

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

If you see error messages, make sure that you are running the program with python, not python3, and are using the sudo command.

Open a browser window from any machine on your network, even the Raspberry Pi itself, and navigate to the IP address of the Raspberry Pi (see Recipe 2.2). The web interface shown in Figure 16-3 should appear.

rpck 0918
Figure 16-3. A web interface to GPIO

If you click one of the three LED buttons at the bottom of the screen, you should find that the appropriate LED toggles on and off.

Also, if you hold down the button as you reload the web page, you should see that the text next to Button says Down rather than Up.

Discussion

To understand how the program works, we first need to look at how a web interface works. All web interfaces rely on a server somewhere (in this case, a program on the Raspberry Pi) responding to requests from a web browser.

When the server receives a request, it looks at the information that comes with the request and formulates some HyperText Markup Language (HTML) in response.

If the web request is just to the root page (for my Raspberry Pi, the root page is http://192.168.1.8/), led_number will be given a default value of n. However, if we were to browse the URL http://192.168.1.8/2, the 2 on the end of the URL would be assigned to the led_number parameter.

The led_number parameter is then used to determine that LED 2 should be toggled.

To be able to access this LED-toggling URL, we need to arrange things so that when the button for LED 2 is pressed, the page is reloaded with this extra parameter on the end of the URL. The trick here is to include a JavaScript function in HTML that is returned to the browser. When the browser runs this function, it causes the page to be reloaded with the appropriate extra parameter.

This all means that we have a rather mind-bending situation in which the Python program is generating code in JavaScript to be run later by the browser. The lines that generate this JavaScript function are as follows:

    response = "<script>"
    response += "function changed(led)"
    response += "{"
    response += "  window.location.href='/' + led"
    response += "}"
    response += "</script>"

We need to also generate the HTML that will eventually call this script when a button is pressed. Rather than repeat the HTML for each of the web page buttons, this is generated by the function html_for_led:

def html_for_led(led):
    i = str(led)
    result = " <input type='button' onClick='changed(" + i + ")'
    value ='LED " + i + "'/>"
    return result

This code is used three times, once for each button, and links a button press with the changed function. The function is also supplied with the LED number as its parameter.

The process of reporting the state of the push button tests to see whether the button is pressed and reports the appropriate HTML.

See Also

For more information on using bottle, see the bottle documentation.

16.2 Displaying Sensor Readings on a Web Page

Problem

You want to display sensor readings from your Raspberry Pi on a web page that automatically updates.

Solution

Use the bottle web server and some fancy JavaScript to automatically update your display.

The example shown in Figure 16-4 displays the Raspberry Pi’s CPU temperature using its built-in sensor.

F1402
Figure 16-4. Displaying the Raspberry Pi CPU temperature

To install the bottle library, see Recipe 7.17.

There are four files for this example, and all of them are contained in the folder ch_16_web_sensor:

web_sensor.py

Contains the Python code for the bottle server

main.html

Contains the web page that will be displayed in your browser

justgage.1.0.1.min.js

A third-party JavaScript library that displays the temperature meter

raphael.2.1.0.min.js

A library used by the justgage library

To run the program, change directory to ch_16_web_sensor.py and then run the Python program using the following:

$ sudo python web_sensor.py

As with all the program examples in this book, you can also download this program (see Recipe 3.22).

Then open a browser, either on the same Raspberry Pi or on any computer on the same network as the Raspberry Pi, and enter the IP address of the Raspberry Pi into the browser’s address bar. The page shown in Figure 16-4 should appear.

Discussion

The main program (web_sensor.py) is actually quite concise:

import os, time
from bottle import route, run, template

def cpu_temp():
    dev = os.popen('/opt/vc/bin/vcgencmd measure_temp')
    cpu_temp = dev.read()[5:-3]
    return cpu_temp

@route('/temp')
def temp():
    return cpu_temp()

@route('/')
def index():
    return template('main.html')

@route('/raphael')
def index():
    return template('raphael.2.1.0.min.js')

@route('/justgage')
def index():
    return template('justgage.1.0.1.min.js')

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

The function cpu_temp reads the temperature of the Raspberry Pi’s CPU, as described in Recipe 13.10.

Four routes are then defined for the bottle web server. The first (/temp) returns a string containing the CPU temperature in degrees C. The root route (/) returns the main HTML template for the page (main.html). The other two routes provide access to copies of the raphael and justgage JavaScript libraries.

The file main.html mostly contains the JavaScript to render the user interface:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" 
type="text/javascript" charset="utf-8"></script>
<script src="raphael"></script>
<script src="justgage"></script>

<script>
function callback(tempStr, status){
if (status == "success") {
    temp = parseFloat(tempStr).toFixed(2);
    g.refresh(temp);
    setTimeout(getReading, 1000);
}
else {
    alert("There was a problem");
    }
}

function getReading(){
    $.get('/temp', callback);
}
</script>
</head>

<body>
<div id="gauge" class="200x160px"></div>

<script>
var g = new JustGage({
    id: "gauge",
    value: 0,
    min: 10,
    max: 60,
    title: "CPU Temp 'C"
});
getReading();
</script>

</body>
</html>

The jquery, raphael, and justgage libraries are all imported (jquery from https://developers.google.com/speed/libraries/#jquery, and the other two from local copies).

Getting a reading from the Raspberry Pi to the browser window is a two-stage process. First, the function getReading is called. This sends a web request with the route /temp to web_sensor.py and specifies a function called callback to be run when the web request completes. The callback function is then responsible for updating the justgage display before setting a timeout to call getReading again after a second.

See Also

For an example of using a Python app to display sensor values in an application rather than a web page, see Recipe 13.22.

The justgage library has all sorts of useful options for displaying sensor values. See http://justgage.com/ for more information.

16.3 Getting Started with Node-RED

Problem

You want to create simple IoT workflows, such as sending a tweet when a button is pressed on your Raspberry Pi.

Solution

Use the Node-RED system that is preinstalled on Raspbian. Use the following example to start a Node-RED server running:

$ node-red-pi --max-old-space-size=256

Then connect to the server using a browser. This can be on the Raspberry Pi itself, in which case you can connect to the URL http: //127.0.0.1:1880/—or if you are connecting from another computer on your network, change 127.0.0.1 to the local IP address of your Raspberry Pi. Figure 16-5 shows the sort of thing you can expect to see in your browser when you connect to the Node-RED server.

Figure 16-5. The Node-RED web interface

The idea behind Node-RED is that you draw your program (called a flow) rather than write code. To do this, you drag nodes onto the editor area and then connect them together. For example, Figure 16-5 shows a minimal flow with two Raspberry Pi pins linked together. One pin acts as an input and might be connected to a switch (let’s pick GPIO 25 as an example), and the other is connected to an LED (let’s assume GPIO 18). You can accomplish this using a Squid LED and button as in Recipe 16.1.

The node on the left, labeled PIN 22 is the input (connected to the switch on GPIO 25), and PIN 12 the output (connected to the LED on GPIO 18). Node-RED uses the pin positions rather than the GPIO names.

To create this flow in your editor, scroll down the list of nodes on the left until you get to the Raspberry Pi section. Drag the “rpi gpio” node with the Raspberry Pi icon on its left to the editor area. This will be the input. Double-click it to open the window shown in Figure 16-6. Select “22 - GPIO25” and then click Done.

Figure 16-6. Selecting GPIO 25 in Node-RED

Next, select the other “rpi gpio” node type (with the Raspberry Pi symbol on the right) and drag it to the editor area, and then double-click it to open the window shown in Figure 16-6; this time select “12 - GPIO18,” and then click Done.

Link the two nodes together by dragging out from the round connector on the right of the input node, so that the flow looks like Figure 16-5.

Assuming that you have a push switch and LED connected to your Raspberry Pi, you can now run this flow by clicking on the Deploy button. The LED should light, and when you press the button the LED should turn off. The logic of this is inverted, but let’s leave that for now. We revisit this in the next chapter, where you learn a lot more about Node-RED.

This is all very neat, but as yet it does not have much to do with the IoT. This is where some of the other node types of Node-RED come into play. If you look up and down the list, you will find all sorts of nodes, including the Tweet node. You can connect this node as a second output to the PIN 22 node, so that the flow now looks like Figure 16-7. Double-click the Tweet node to configure it with your Twitter credentials. Now when you press the button, a tweet will be sent.

Figure 16-7. Sending tweets from Node-RED

Discussion

Node-RED is an extremely powerful system, and consequently, becoming familiar with all its features and its odd quirks will take some time. As well as creating direct flows like the one we made here, you can also introduce switching code (like an if statement) and functions that transform the messages being passed between the nodes.

We have only just touched on Node-RED here; if you want to learn more, I suggest working through the documentation mentioned in the See Also section and much of Chapter 17.

Having played with Node-RED and decided that you like it, you may well want to ensure that it starts automatically whenever your Raspberry Pi reboots by issuing the following commands:

$ sudo systemctl enable nodered.service
$ sudo systemctl start nodered.service

See Also

More information is available in the full documentation on using Node-RED on the Raspberry Pi.

Here are some good video introductions to Node-RED: https://oreil.ly/uxGHZ and https://oreil.ly/ZSDNi.

16.4 Sending Email and Other Notifications with IFTTT

Problem

You want a flexible way for your Raspberry Pi to send notifications through email, Facebook, Twitter, or Slack.

Solution

Have your Raspberry Pi send requests to the If This Then That (IFTTT) Maker channel to trigger configurable notifications.

This recipe is illustrated with an example that sends you an email when the CPU temperature of your Raspberry Pi exceeds a threshold.

You need to create an account with IFTTT before you can begin using it, so visit www.ifttt.com and sign up.

The next step is to create a new IFTTT Applet. An Applet is like a rule, such as When I get a web request from a Raspberry Pi, send an email. Click the “Create an Applet” button. This will prompt you to first enter the THIS part of the recipe and later the THAT part.

In this case, the IF THIS part (the trigger) is going to be the receipt of a web request from your Raspberry Pi, so click THIS and then enter Webhooks into the search field to find the Webhooks channel. Select the Webhooks channel, and when prompted, select the option “Receive a web request.” This opens the form shown in Figure 16-8.

Figure 16-8. The “Receive a web request” trigger form

In the Event Name field, enter the text cpu_too_hot and then click “Create trigger.”

This will now move you to the THAT portion of the recipe, the action, and you will need to select an action channel. There are many options, but for this example you will use the Email channel, so in the search field, type Email and then select the Email channel.

Having selected the Email channel, select the action “Send me an email,” which displays the form shown in Figure 16-9.

Figure 16-9. Completing the action fields in IFTTT

Change the text so that it appears as shown in Figure 16-9. Note that the special values OccurredAt and Value1 will both be surrounded by {{ and }}. These values are called ingredients and are variable values that will be taken from the web request and substituted into the email subject and body.

Click “Create action” and then Finish to complete the recipe creation.

One final piece of information that we need is the API (application programming interface) key for the Webhooks channel. This is so that other people can’t bombard you with emails about their Raspberry Pi’s CPU temperature.

To find this key on the IFTTT website, click the Services tab on the My Applets page and then find Webhooks. On the Webhooks page, click Documentation, and a page like Figure 16-10 displays; here you can see your key (which is intentionally obscured in this figure). You will need to paste this key into the code that follows Figure 16-10, in the line KEY = 'your_key_here'.

Figure 16-10. Finding your API key

The Python program to send the web request is called ch_16_ifttt_cpu_temp.py:

import time, os 
import requests

MAX_TEMP = 37.0
MIN_T_BETWEEN_WARNINGS = 60 # Minutes

EVENT = 'cpu_too_hot'
BASE_URL = 'https://maker.ifttt.com/trigger/'
KEY = 'your_key_here'

def send_notification(temp):
    data = {'value1' : temp}
    url = BASE_URL + EVENT + '/with/key/' + KEY
    response = requests.post(url, json=data)
    print(response.status_code)

def cpu_temp():
    dev = os.popen('/opt/vc/bin/vcgencmd measure_temp')
    cpu_temp = dev.read()[5:-3]
    return float(cpu_temp)
    
while True:
    temp = cpu_temp()
    print("CPU Temp (C): " + str(temp))
    if temp > MAX_TEMP:
        print("CPU TOO HOT!")
        send_notification(temp)
        print("No more notifications for: " + str(MIN_T_BETWEEN_WARNINGS) +
              " mins")
        time.sleep(MIN_T_BETWEEN_WARNINGS * 60)
    time.sleep(1)

As with all the program examples in this book, you can also download this program (see Recipe 3.22).

I have left the MAX_TEMP deliberately low for testing purposes. If you live somewhere hot, you will want to bump this number up to 60 or 70.

Paste the key into ch_16_ifttt_cpu_temp.py on the line that starts KEY= and then run the program using:

$ python3 ch_16_ifttt_cpu_temp.py

You can increase your CPU temperature by playing a video or temporarily wrapping your Raspberry Pi in Bubble Wrap. When the event is triggered, you should receive an email that looks like Figure 16-11. Notice how the values have been substituted into the email (again, the obscuring is intentional).

Figure 16-11. A notification email

Discussion

Most of the action for this program takes place in the send_notification function. This function first constructs a URL that includes the key and request parameter value1 (containing the temperature) and then uses the Python requests library to send the web request to IFTTT.

The main loop continually checks the CPU temperature against the MAX_TEMP; if the temperature exceeds MAX_TEMP, the web request is sent, and a long sleep is started as specified by MIN_T_BETWEEN_WARNINGS. The sleep prevents your inbox from being flooded with notifications.

As an alternative to using IFTTT, you could, of course, just send an email directly using Recipe 7.16. However, by using IFTTT to send the messages, you are not restricted to email notifications—you could use any of the action channels available in IFTTT without having to write any code.

See Also

To send an email directly from Python, see Recipe 7.16.

The code to measure the CPU temperature is described in Recipe 13.10.

16.5 Sending Tweets Using ThingSpeak

Problem

You want to automatically send tweets from your Raspberry Pi—for example, to irritate people by telling them the temperature of your CPU.

Solution

You could just use Recipe 16.4 and change the action channel to be Twitter. However, the ThingSpeak service is an alternative way of doing this.

ThingSpeak is similar to IFTTT but is aimed squarely at IoT projects. It allows you to create channels that can store and retrieve data using web requests, and it also has a number of actions, including ThingTweet, which provides a web services wrapper around Twitter. This is easier to use than the Twitter API, which requires you to register your application with Twitter.

Start by visiting https://thingspeak.com and signing up. Note that this also involves creating a MATLAB account for no particularly good reason.

Next, select the ThingTweet action from the Apps menu. You are prompted to log in to Twitter, and then your action will become activated (Figure 16-12).

F1407
Figure 16-12. The ThingTweet action

The Python program to send the web request that triggers the tweet is called ch_16_send_tweet.py.

import time, os 
import requests

MAX_TEMP = 37.0
MIN_T_BETWEEN_WARNINGS = 60 # Minutes

BASE_URL = 'https://api.thingspeak.com/apps/thingtweet/1/statuses/update/'
KEY = 'your_key_here'

def send_notification(temp):
    status = 'Thingtweet: Raspberry Pi getting hot. CPU temp=' + str(temp)
    data = {'api_key' : KEY, 'status' : status}
    response = requests.post(BASE_URL, json=data)
    print(response.status_code)

def cpu_temp():
    dev = os.popen('/opt/vc/bin/vcgencmd measure_temp')
    cpu_temp = dev.read()[5:-3]
    return float(cpu_temp)
    
while True:
    temp = cpu_temp()
    print("CPU Temp (C): " + str(temp))
    if temp > MAX_TEMP:
        print("CPU TOO HOT!")
        send_notification(temp)
        print("No more notifications for: " + str(MIN_T_BETWEEN_WARNINGS) +
              " mins")
        time.sleep(MIN_T_BETWEEN_WARNINGS * 60)
    time.sleep(1)

As with all the program examples in this book, you can also download this program (see Recipe 3.22).

As with Recipe 16.4, you need to paste your key from Figure 16-12 into the code before you run the program. Run and test the program in the same way you did in Recipe 16.4.

Discussion

The code is very similar to Recipe 16.4. The main difference is in the function send_notification, which constructs the tweet and then sends the web request with the message as the parameter status.

See Also

More information is available in the full documentation of the ThingSpeak service.

In Recipe 16.6, you use the popular CheerLights, implemented in ThingSpeak; in Recipe 16.7, you learn how to use ThingSpeak to collect sensor data.

16.6 CheerLights

Problem

You want to hook your Raspberry Pi up to an RGB LED and participate in the popular CheerLights project.

CheerLights is a web service that, when anyone sends a tweet to @cheerlights containing the name of a color, will record that color as being the CheerLights color. Around the world, many people have CheerLights projects that use a web service to request the last color and set their lighting to that color. So when anyone tweets, everyone’s lights change color.

Solution

Use a Raspberry Squid RGB LED connected to your Raspberry Pi (Figure 16-13) and run the test program called ch_16_cheerlights.py (shown after Figure 16-13).

F1408
Figure 16-13. A CheerLights display
from gpiozero import RGBLED
from colorzero import Color
import time, requests

led = RGBLED(18, 23, 24)
cheerlights_url = "http://api.thingspeak.com/channels/1417/field/2/last.txt"

while True:
    try:
        cheerlights = requests.get(cheerlights_url) 
        c = cheerlights.content            
        print(c)                    
        led.color = Color(c)
    except Exception as e:
        print(e)
    time.sleep(2)

As with all the program examples in this book, you can also download this program (see Recipe 3.22).

When you run the program, your LED should immediately set itself to a color. It will probably change color after a while when someone tweets; if it doesn’t, try tweeting a message such as “@cheerlights red,” and the color of your LED and the rest of the world’s LEDs should change. Valid color names for CheerLights are red, green, blue, cyan, white, oldlace, purple, magenta, yellow, orange, and pink.

Discussion

The code just sends a web request to ThingSpeak, which returns a string of colors as a 6-digit hexadecimal number. This is then used to set the LED color.

The try/except code is used to ensure that the program does not crash if there is a temporary network outage.

See Also

CheerLights uses ThingSpeak to store the last color in a channel. In Recipe 16.7, a channel is used to record sensor data.

If you don’t have a Squid, you can use an RGB on a breadboard (see Recipe 10.10), or you can even adapt Recipe 14.6 to control an entire LED strip.

16.7 Sending Sensor Data to ThingSpeak

Problem

You want to log sensor data to ThingSpeak and then see charts of the data over time.

Solution

Log in to ThingSpeak, and from the Channels drop-down, select My Channels. Next, create a new channel by completing the top of the form, as shown in Figure 16-14.

You can leave the rest of the form blank. When you have finished editing, click Save Channel at the bottom of the page. Click the API Keys tab to find a summary of the web requests that you can use, along with keys for the channel you just created (Figure 16-15).

F1409
Figure 16-14. Creating a channel in ThingSpeak
F1410
Figure 16-15. Getting data into a ThingSpeak channel

You will need to copy your API key (Write key) as the value for KEY in the program that follows.

To send data to the channel, you must send a web request. The Python program to send the web request is called ch_16_thingspeak_data.py:

import time, os 
import requests


PERIOD = 60 # seconds
BASE_URL = 'https://api.thingspeak.com/update.json'
KEY = 'your key here'

def send_data(temp):
    data = {'api_key' : KEY, 'field1' : temp}
    response = requests.post(BASE_URL, json=data)

def cpu_temp():
    dev = os.popen('/opt/vc/bin/vcgencmd measure_temp')
    cpu_temp = dev.read()[5:-3]
    return float(cpu_temp)

while True:
    temp = cpu_temp()
    print("CPU Temp (C): " + str(temp))
    send_data(temp)
    time.sleep(PERIOD)

As with all the program examples in this book, you can also download this program (see Recipe 3.22).

Run the program. On the ThingSpeak channel page, on the Private View tab, you should see a graph like the one shown in Figure 16-16.

F1411
Figure 16-16. Charting the sensor data

This will update every minute as each new reading arrives.

Discussion

The variable PERIOD is used to determine the time interval after each sending of the temperature. This period is in seconds.

The send_data function constructs the web request, supplying the temperature in a parameter called field1.

If your data might be something of public interest—say, accurate environmental readings—you might want to make the channel public so that anyone can make use of it. This probably isn’t the case for your Pi’s CPU temperature.

See Also

For an example of exporting sensor data into a spreadsheet, see Recipe 13.23.

For an explanation of the code that reads the CPU temperature, see Recipe 13.10.

16.8 Responding to Tweets Using Dweet and IFTTT

Problem

You want your Raspberry Pi to perform some action in response to a certain hashtag or mention in a tweet.

Recipe 16.6 does this, but it does it very inefficiently because it relies on you continually polling with web requests to see whether the color has changed.

Solution

An efficient mechanism for monitoring tweets that does not rely on polling is to use IFTTT (see Recipe 16.4) to spot tweets of interest and then send a web request to a service called Dweet that can push notifications to a Python program running on your Raspberry Pi (Figure 16-17).

For example, you could flash an LED for 10 seconds every time there is a mention of your username on Twitter by using a Raspberry Squid or an LED attached to a breadboard.

As far as the hardware goes, this recipe just requires some electronics that do something noticeable when GPIO 18 goes high. This could be one channel of a Raspberry Squid (see Recipe 9.10) or a single LED attached to breadboard (see Recipe 10.1) or, for ultimate flexibility, a relay (see Recipe 10.5). Using a relay would allow you to create a project like Bubblino, the bubble-blowing Arduino bot.

F1412
Figure 16-17. IFTTT, Dweet, and Python, working together

The first step is to log in to IFTTT (see Recipe 16.4) and then create a new Applet. Choose an action channel of “New Mention of You” and then click “Create trigger.” For the recipe’s action channel, select Webhooks, and then select the action “Make a web request” and complete the fields, as shown in Figure 16-18.

The URL includes a request parameter with the ingredient of “text.” This will contain the body of the tweet. Although this will not be used other than to print it in the console, you might have the message displayed on an LCD screen for a more sophisticated project, so it is useful to know how to pass data from a tweet to the Python program.

Finally, click “Create recipe” to take the IFTTT recipe live.

The dweet.io web service operates rather like Twitter for IoT things. It has a web interface that allows you to both post and listen for dweets. Dweet does not require an account or any login details to make use of it; you can just have one thing (IFTTT, in this case) send a message to Dweet and have another thing (your Raspberry Pi Python program) wait for a notification from the service that something you are interested in has happened. In this case, the token that links the two is tweet_about_me. This is not very unique, and if several people are trying out this example from the book at the same time, you will all get one another’s messages. To avoid this, use a more unique token (say, by adding a random string of letters and numbers to the message).

Figure 16-18. Completing the “Make a web request” action channel in IFTTT

To access Dweet from your Python program, you need to install the dweepy library by using the following command:

$ sudo pip3 install dweepy

The program for this recipe is called ch_16_twitter_trigger.py:

import time
import dweepy
from gpiozero import LED

KEY = 'tweet_about_me'
led = LED(18)

while True:
    try:
        for dweet in dweepy.listen_for_dweets_from(KEY):
            print('Tweet: ' + dweet['content']['text'])
            led.on()  
            time.sleep(10)
            led.off()
    except Exception:
        pass

As with all the program examples in this book, you can also download this program (see Recipe 3.22).

After it’s running, try mentioning yourself in a tweet, and the LED should light for 10 seconds.

Discussion

The program uses the listen_for_dweets_from method to leave an open connection to the dweet.io server, listening for any push messages from the server as a result of a dweet arriving from IFTTT in response to a tweet. The try/except block ensures that if there is any communication outage, the program will just start the listening process again.

See Also

For a similar project using a different approach, see Recipe 16.6.

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

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