Chapter 3
The Tweetin’ Onion

Now that we’ve had an introduction to how the Omega2 works and how to interface with it, let’s create a few projects.

The Temperature Tweet

For the first project, I’d like you to remember the O2’s roots as an interface to the Internet of Things (IoT). With that in mind, let’s use an external sensor to read the temperature in the room, and then create a Twitter account (or use our own) and use Twitter’s API to tweet the temperature results every so often.

The temperature sensor I’m using here is the DS18B20 one-wire temperature sensor, available from both Jameco and Amazon. This one is useful because it’s small, cheap, and easy to interface with (note the one-wire in the name). Also, the kind folks at Onion have already done the hard work for us of writing a library (in Python, even!) to interface with the DS18B20. We’ll reuse their code in our little application here. (Remember: Programmers are inherently lazy. Don’t reinvent the wheel if you don’t have to.)

Install Modules

The first thing we’ll need to do is install the Python modules we’ll need, which will allow us to interact with the Onion’s GPIO pins. Connect to your O2 via either the console or an SSH session, and in your terminal, enter

opkg update

followed by

opkg install pyOnionGpio

If you’d like to write your code in a terminal session on your Onion, vi comes preinstalled. If you like, you can also install nano, the text editor:

opkg install nano

This is not a requirement; you are free to use the Editor tab in the console or even write your code on your local desktop/laptop and upload it via the Editor or the scp command if you’d prefer. I just find it easier to do my development on the machine for which I’m developing. It’s pretty easy to switch back and forth between

nano main.py

and

python main.py

as your code develops.

The Twitter Side of Things

In order to interact easily with Twitter’s API, we’re going to download and use a great tool called Twython, developed by Ryan McGrath and Mike Helmick. It’s available using pip, so if you’ve installed pip (as you should have if you were following along in Chapter 2) simply enter

pip install twython 

in your terminal. Once it’s installed (which can take a little while—remember that the Onion doesn’t have a whole lot of processing power), it’s available to you in your Python program. If you want to test it, in your O2’s terminal enter

python

and then type

>>> import twython

at the prompt and make sure no errors are returned.

Now that Twython is installed on your Omega2, go to http://apps.twitter.com. Log into your account, or create a Twitter account if you don’t have one already. Then click the Create New App button on the right side of the page.

Now you’ll need to fill in your application details, starting with the name of the app (Figure 3-1). It’s probably to your advantage to name it something memorable, like OnionTweetTemp, so you can find it easily. Then fill in the Description and Website fields, which are both required. (If you don’t have a website, you can use a placeholder such as http://www.example.com for this field.) Then check the Developer Agreement box and create your application.

c03f001.tif

Figure 3-1: Creating a Twitter app

Now you’ll be greeted by your app’s management page. Make sure that everything you see on the page is correct, and then go to the Keys And Access Tokens tab. You’ll need the Consumer Key and the Consumer Secret for your application, and you’ll also need an access token, which hasn’t been created yet. Scroll to the bottom and click Create My Access Token, which will allow your app to post status updates to your Twitter account. Finally, when that’s completed, make sure that your application has Read and Write access level permissions (Figure 3-2).

c03f002.tif

Figure 3-2: Twitter application permissions

Got all that? Good. Now, let’s go back to the Omega.

The Hardware

For this project, you’ll need your Omega2 and an expansion board, a DS18B20 sensor, a 5kΩ (or thereabouts) resistor, a small breadboard, and some jumper wires.

Start by plugging the sensor into your breadboard. Looking at the sensor from the front (the flat side), the three pins are GND, Data, and VDD (Figure 3-3).

c03f003.tif

Figure 3-3: The DS18B20 sensor

Next, connect the resistor between pins 2 and 3, which has the effect of pulling the input HIGH between data reads. Now, using your jumper wires, connect the GND pin to one of your board’s ground pins, the VDD pin to a 3.3V pin, and the Data pin (DQ) to GPIO pin 19. Your final setup should look something like Figure 3-4.

c03f004.tif

Figure 3-4: Connected temperature sensor

The Code

Now that Twitter’s been set up and your hardware is connected, it’s time to look at the code. As I stated earlier, I’m using some of the code written by the Onion’s coding group as a base template; we’ll download the three files we need and then modify them to do what we want.

Start by creating a folder on your O2 and cding into it:

mkdir OnionTweetTemp
cd OnionTweetTemp

Now download the files we need:

wget https://raw.githubusercontent.com/OnionIoT/temperature-monitor/master/temperatureSensor.py
wget https://raw.githubusercontent.com/OnionIoT/temperature-monitor/master/oneWire.py
wget https://raw.githubusercontent.com/OnionIoT/temperature-monitor/master/main.py

Each of those wget commands is one line. You can put them all in one command if you like; it just shows up better in print if I break it into three downloads.

We don’t need to change oneWire.py and temperatureSensor.py; they’re the code libraries necessary to communicate with the DS18B20. oneWire.py does the actual communicating with the sensor, and temperatureSensor.py creates an object of the temperatureSensor class and returns the value read (in Celsius). Instead, let’s open main.py and change and delete a few things:

nano main.py

We don’t need to import os, json, ubidots, or oledHelper, so remove those lines. Nor do we need to import config, define a dirName, open the config file, or create a token or deviceName. So your main.py should contain only the following lines before def __main__():

import oneWire
import temperatureSensor
oneWireGpio = 19

What we do need, however, is some Twitter stuff. Add another import statement:

from twython import Twython

and declare your app’s keys:

app_key = "<Your App Key Here>"
app_secret = "<Your App Secret Key Here>"
oauth_token = "<Your OAUTH Token Here>"
oauth_secret = "<Your OAUTH Secret Here>"
twitter = Twython(app_key, app_secret, oauth_token, oauth_secret)

and now your main function should look something like this:

def __main__():
    if not oneWire.setupOneWire(str(oneWireGpio)):
        print "Kernel module could not be inserted. Please reboot and try again."
        return -1
    # get the address of the temperature sensor
    #     it should be the only device connected in this experiment
    sensorAddress = oneWire.scanOneAddress()
    # instantiate the temperature sensor object
    sensor = temperatureSensor.TemperatureSensor("oneWire", {"address": sensorAddress, "gpio": oneWireGpio })
    if not sensor.ready:
        print "Sensor was not set up correctly. Please make sure that your sensor is firmly connected to the GPIO specified above and try again."
        return -1
    # check and print the temperature
    temperature = sensor.readValue()
    dataPoint = {"temperature": temperature}
    # temperature is in deg C
    # To change to deg F, add following line:
    temperature = temperature * (9.0/5.0) + 32.0
    
    # Post to Twitter
    twitter.update_status(status="Current Omega2 temperature: " + str(temperature))

Finish the program with

if __name__ == '__main__':
    __main__()

and we’re done. You can download this edited and shortened version of main.py at

https://github.com/wdonat/jumpstarting_onion/blob/master/Chapter3/main.py

The other two files are hosted there as well.

So what does this program do? As I said earlier, it uses the oneWire and temperatureSensor files to communicate with the sensor and create an object that we can interact with and read. In that sense, think of those two files as if they were Arduino libraries you had to install.

After we declare our Twitter keys and authorizations, Twython has a simple update_status() function that takes a string (or strings) as an argument and posts to your Twitter feed. To test it, make sure you’re in your OnionTweetTemp directory and that all three files are also there. Then just run

python main.py

Wait for a few moments and then check your Twitter dashboard. You should see something like Figure 3-5.

c03f005.tif

Figure 3-5: Success!

If it didn’t work, double-check your keys and authorization tokens. I’ve read about more than a few app developers who even had to regenerate these a few times before they could get their applications to authenticate and run correctly.

Once that’s done, congratulations! Your Omega2 can now read from an external sensor and let you know about it via Twitter—the very essence of what the IoT is about! This is obviously a basic implementation of this functionality; to improve it, I suggest adding things like a loop, letting it tweet every hour, for instance. Or, even better, continuously monitor the temperature, and if it changes more than a set amount over a set period of time, tweet about it.

In our last chapter, we’re going to put our Omega2 on a mobile robotic platform and allow it to roam free!

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

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