Chapter 8. The Internet of Things
In this chapter, we will cover the following recipes:
- Location-based recipes – hooking up GPS
- Location-based recipes – Bluetooth LE and Beacons
- Using sensors and data with ThingSpeak
- Making things smarter – building a wireless digital picture frame
Introduction
The Internet of Things is a large basketful of things. It is in fact so large that no one can see its edges yet. It is an evolving and quickly expanding repo of products, concepts, fledgling business ventures, prototypes, middleware, ersatz systems, and hardware.
Some define IoT as connecting things that are not normally connected, thus making them a bit more useful than they were as unconnected devices.
We will not show you how to turn off the lights in your house using the BBB, or how to autoraise the garage door when you drive onto your street. There are a bunch of tutorials that do that already. Instead, we will take a look at some of the recipes that provide some fundamental elements for building IoT-centric prototypes or demos.
Location-based recipes – hooking up GPS
A common question in the IoT realm: where is that darn thing? That Internet of Things thing? Being able to track and pinpoint the location of a device is one of the most typical features of many IoT use cases. So, we will first take a look at a recipe on how to use everyone's favorite location tech: GPS. Then, we will explore one of the newer innovations that has spun out of Bluetooth 4.0, beacons, a technology for capturing more precise location-based data than GPS.
The UART background
In the galaxy of embedded systems, developers use dozens of different serial protocols. More common and familiar to most consumers are components such as USB and Ethernet. Then, there are protocols familiar to engineers, such as SPI and I2C, which we have already explored in this book. For this recipe, we will use yet another flavor of serial, UART, an asynchronous or clock-less protocol. This comes in handy in a variety of scenarios to connect IoT-centric devices.
Universal asynchronous receiver/transmitter (UART) is a common circuit block used for managing serial data and hardware. As UART does not require a clock signal, it uses fewer wires and pins. In fact, UART uses only two serial wires: RX to receive packets and TX to transmit them.
The framework for this recipe comes from AdaFruit's tutorial for the RPi. However, the difference between these two boards are nontrivial, so this recipe needs quite a few more ingredients than the RPi version.
Getting ready
You will need the following components for this recipe:
- GPS PCB: You can probably find cheaper versions, but we will use AdaFruit's well-regarded and ubiquitous PCB (http://www.adafruit.com/product/746 at around USD $40.00).
- Antenna: Again, Adafruit's suggested SMA to the uFL adapter antenna is the simplest and cheap at USD $3.00 (https://www.adafruit.com/product/851)
- 5V power: Powering via the 5V DC in lieu of simply connecting via the mini USB is advisable. The GPS modules consume a good bit of power, a fact apparent to all of us, given how the GPS functionality is a well-known drain on our smartphones.
- Internet connectivity via Wi-Fi or Ethernet.
- Breadboard.
- 4x jumper wires.
How to do it…
For the GPS setup, the steps are as follows:
- Insert the PCB pins into the breadboard and wire the pins according to the following fritzing diagram:
P9_11 (blue wire): This denotes RX on BBB and TX on GPS PCB. At first, it may seem confusing to not wire TX to TX, and so on. However, once you understand the pin's function, the logic is clear: a transmit (TX) pin pairs with a pin that can receive data (RX), whereas a receive pin pairs with a pin that transmits data.
P9_13 (green wire): This specifies TX on BBB and RX on GPS PCB
P9_1: This indicates GND
P9_3: This specifies 3.3V
- Now, carefully attach the antenna to the board's uFL connector.
- Next, power your BBB. Here's where it gets a bit tricky.
When your BBB starts, you will immediately see the Fix button on the GPS board that will begin to flash quickly, approximately 1x per second. We will come back to check the integrity of the module's satellite connection in a later step.
- In order to gain access to the UART pins on the BBB, we have to enable them using a Device Tree overlay. Until recently, this was a multistep process. However, now that the BeagleBone Universal I/O package comes preloaded on the current versions of the firmware, enabling the pins (in the case, UART4) in a snap. Let's begin by logging in as root with the following command:
$ sudo -i
- Then, run the relevant Universal I/O command and check whether it went to the right place, as shown in the following code:
# config-pin overlay BB-UART4 # cat /sys/devices/bone_capemgr.*/slots
- Now, reboot your BBB and check whether the device is present in the device list by using the following command:
$ ls -l /dev/ttyO* crw-rw---- 1 root tty 247, 0 Mar 1 20:46 /dev/ttyO0 crw-rw---T 1 root dialout 247, 4 Jul 13 02:12 /dev/ttyO4
- Finally, check whether it is loading properly with the following command:
$ dmesg
This is how the output should look:
[ 188.335168] bone-capemgr bone_capemgr.9: part_number 'BB-UART4', version 'N/A' [ 188.335235] bone-capemgr bone_capemgr.9: slot #7: generic override [ 188.335250] bone-capemgr bone_capemgr.9: bone: Using override eeprom data at slot 7 [ 188.335266] bone-capemgr bone_capemgr.9: slot #7: 'Override Board Name,00A0,Override Manuf,BB-UART4' [ 188.335355] bone-capemgr bone_capemgr.9: slot #7: Requesting part number/version based 'BB-UART4-00A0.dtbo [ 188.335370] bone-capemgr bone_capemgr.9: slot #7: Requesting firmware 'BB-UART4-00A0.dtbo' for board-name 'Override Board Name', version '00A0' [ 188.335400] bone-capemgr bone_capemgr.9: slot #7: dtbo 'BB-UART4-00A0.dtbo' loaded; converting to live tree [ 188.335673] bone-capemgr bone_capemgr.9: slot #7: #2 overlays [ 188.343353] 481a8000.serial: ttyO4 at MMIO 0x481a8000 (irq = 45) is a OMAP UART4 [ 188.343792] bone-capemgr bone_capemgr.9: slot #7: Applied #2 overlays.
Note
Tips to get a GPS Fix
Your best method to get the GPS module connected is to take it outdoors. However, as this is not a likely option when you develop a project, putting it against or even just outside a window will often suffice. If it is cloudy, and if you don't have a reasonably clear sky view from your module's antenna, do not expect a quick connection. Be patient. When a fix is made, the flashing LED will cycle very slowly at about 15-second intervals.
Even if GPS modules do not have a fix, be aware that they will still send data. This can be confusing because you may run some of the following commands and think that your connection is fine, but you just keep getting junk (blank) data. However, to reiterate, the flashing LED needs to have slowed down to 15-second intervals to verify that you have a fix.
- Although the output is not pretty, the following command is a useful first step in making sure that your devices are hooked up because it will show the raw NMEA data coming out of the GPS:
$ cat /dev/ttyO4
Note
NMEA - The National Marine Electronics Associations' GPS language protocol standard.
- Verify that your wiring is correct and that the module is generating data properly (irrespective of a satellite fix) as follows:
$ sudo screen /dev/ttyO4 9600
The output should immediately begin and look something similar to this:
$GPGGA,163356.000,4044.0318,N,07400.1854,W,1,5,2.65,4.0,M,-34.2,M,,*67 $GPGSA,A,3,13,06,10,26,02,,,,,,,,2.82,2.65,0.95*04 $GPRMC,163356.000,A,4044.0318,N,07400.1854,W,2.05,68.70,031214,,,A*46 $GPVTG,68.70,T,,M,2.05,N,3.81,K,A*09 $GPGGA,163357.000,4044.0322,N,07400.1853,W,1,5,2.65,3.7,M,-34.2,M,,*68 $GPGSA,A,3,13,06,10,26,02,,,,,,,,
- Now, quit the program using one of the the following methods:
Ctrl + a, enter or copy and paste
:quit
with the colon to the highlighted box at the bottom, or press Ctrl + a + k + y.
Installing the GPS toolset
- The next set of ingredients in the recipe consists of installing and testing a common toolset to parse GPS on Linux. As always, before installing something new, it is good practice to update your repos with the following command:
$ sudo apt-get update
- Install the tools, including
gpsd
, a service daemon to monitor your GPS receiver. The package exposes all the data on location, course, and velocity on the TCP port 2947 of your BBB and efficiently parses the NMEA text that pours out of the GPS receiver, as shown in the following command:$ sudo apt-get install gpsd gpsd-clients python-gps
For the preceding code,
gpsd-clients
installs some test clients, andpython-gps
installs the required Python library to communicate withgpsd
via Python scripts.Note
After the installation, you may find it useful to run
man gpsd
and review the package's well-written and informative manual. It not only provides the details around what you just installed, but it also provides the general GPS-related content. - If the planets or communication satellites are aligned, you can run this command from the newly installed toolset and begin to display the GPS data:
$ sudo gpsmon /dev/ttyO4
You should see a terminal GUI that looks similar to the following screenshot:
- To quit, press Ctrl + C or enter
q
and then return (Enter) key. - Now, we will test the other principal tool that you just installed with the following command:
$ sudo cgps -s
The output includes the current date and time in UTC, the latitude and longitude, and the approximate altitude.
Troubleshooting—Part 1
You may run into problems here. Commonly, on a first time set up and running, cgps
may time out, close by itself, and lead you to believe that there is a problem with your setup. If so, the next steps can lead you back on the path to GPS nirvana:
- We will begin by stopping all the running instances of GPS, as shown in the following code:
$ sudo killall gpsd
- Now, let's get rid of any sockets that the
gpsd
commands may have left behind with the following command:$ sudo rm /var/run/gpsd.sock
There is a systemd bug that we will typically need to address.
- Open the systemd GPSD service using the following command:
$ sudo nano /lib/systemd/system/gpsd.service
- Paste this command to the window with the following script:
[Unit] Description=GPS (Global Positioning System) Daemon Requires=gpsd.socket [Service] ExecStart=/usr/sbin/gpsd -n -N /dev/ttyO4 [Install] Also=gpsd.socket
- Then, restart the systemd service as follows:
$ sudo service gpsd start
- You should now be able run either of the following services again:
$ sudo gpsmon /dev/ttyO4
Alternatively, you can run the following command:
$ sudo cgps -s
Troubleshooting—Part 2
Sometimes, the preceding fixes don't fix it. Here are several more suggestions for troubleshooting purposes:
- Set up a control socket for GPS with the following command:
$ sudo gpsd -N -D3 -F /var/run/gpsd.sock
Note
The explanation of the command-line flags or options are as follows:
-N
: This tellsgpsd
to immediately post the GPS data. Although this is useful for testing purposes, it can also drain power, so leave it off if your use case is battery-powered.-F
: This creates a control socket for device addition and removal. The option requires a valid pathname on your local filesystem, which is why our command is appended with/var/run/gpsd.sock
.
- We may also need to install a package that lets us examine any port conflict that could be occurring, as shown in the following command:
$ sudo apt-get install lsof
- This installed utility will open and display the system files, including disk files, named pipes, network sockets, and devices opened by all the processes. There are multiple uses for the tool. However, we only want to determine whether the GPS module is speaking correctly to the port
2947
and if there are any conflicts. So, we will run the following command:$ sudo lsof -i :2947
This is how the output should look:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd 1 root 24u IPv4 6907 0t0 TCP localhost:gpsd (LISTEN) gpsd 5960 nobody 4u IPv4 6907 0t0 TCP localhost:gpsd (LISTEN)
- You may also want to check whether any instances of the GPS are running and then kill them with the following command:
$ ps aux |grep gps $ sudo killall gpsd
For a final bit of cooking with the GPS board, we want to run a Python script and display the data in tidy, parsed output. The code was originally written for the RPi, but it is useable on the BBB as well.
- Go get it with the following command:
$ git clone https://github.com/HudsonWerks/gps-tests.git
- Now, browse to the new directory that we just created and take a look at the file that we will use with the following code:
$ cd gps-tests $ sudo nano GPStest1.py
- Let's peruse the script a bit to understand some of its key parts:
The script requires a number of Python libraries:
import os from gps import * from time import * import time import threading
Keep in mind that getting a fix and then obtaining a good GPS data can take several moments before the system settles into a comfortable flow, as shown in the following code:
#It may take a second or two to get good data #print gpsd.fix.latitude,', ',gpsd.fix.longitude,' Time: ',gpsd.utc
If you find the output overwhelming, you can always modify the print commands to simplify the display as follows:
print print ' GPS reading' print '----------------------------------------' print 'latitude ' , gpsd.fix.latitude print 'longitude ' , gpsd.fix.longitude print 'time utc ' , gpsd.utc,' + ', gpsd.fix.time print 'altitude (m)' , gpsd.fix.altitude print 'eps ' , gpsd.fix.eps print 'epx ' , gpsd.fix.epx print 'epv ' , gpsd.fix.epv print 'ept ' , gpsd.fix.ept print 'speed (m/s) ' , gpsd.fix.speed print 'climb ' , gpsd.fix.climb print 'track ' , gpsd.fix.track print 'mode ' , gpsd.fix.mode print print 'sats ' , gpsd.satellites time.sleep(5)
- Now close the script and run the following command:
$ python GPStest1.py
In a few seconds, the nicely formatted GPS data will be displayed in your terminal window.
There's more...
- Sparkfun's tutorial on GPS is definitely worth the read at https://learn.sparkfun.com/tutorials/gps-basics/all
- For further GPSD troubleshooting, refer to http://www.catb.org/gpsd/troubleshooting.html
Getting ready
You will need the following components for this recipe:
- GPS PCB: You can probably find cheaper versions, but we will use AdaFruit's well-regarded and ubiquitous PCB (http://www.adafruit.com/product/746 at around USD $40.00).
- Antenna: Again, Adafruit's suggested SMA to the uFL adapter antenna is the simplest and cheap at USD $3.00 (https://www.adafruit.com/product/851)
- 5V power: Powering via the 5V DC in lieu of simply connecting via the mini USB is advisable. The GPS modules consume a good bit of power, a fact apparent to all of us, given how the GPS functionality is a well-known drain on our smartphones.
- Internet connectivity via Wi-Fi or Ethernet.
- Breadboard.
- 4x jumper wires.
How to do it…
For the GPS setup, the steps are as follows:
- Insert the PCB pins into the breadboard and wire the pins according to the following fritzing diagram:
P9_11 (blue wire): This denotes RX on BBB and TX on GPS PCB. At first, it may seem confusing to not wire TX to TX, and so on. However, once you understand the pin's function, the logic is clear: a transmit (TX) pin pairs with a pin that can receive data (RX), whereas a receive pin pairs with a pin that transmits data.
P9_13 (green wire): This specifies TX on BBB and RX on GPS PCB
P9_1: This indicates GND
P9_3: This specifies 3.3V
- Now, carefully attach the antenna to the board's uFL connector.
- Next, power your BBB. Here's where it gets a bit tricky.
When your BBB starts, you will immediately see the Fix button on the GPS board that will begin to flash quickly, approximately 1x per second. We will come back to check the integrity of the module's satellite connection in a later step.
- In order to gain access to the UART pins on the BBB, we have to enable them using a Device Tree overlay. Until recently, this was a multistep process. However, now that the BeagleBone Universal I/O package comes preloaded on the current versions of the firmware, enabling the pins (in the case, UART4) in a snap. Let's begin by logging in as root with the following command:
$ sudo -i
- Then, run the relevant Universal I/O command and check whether it went to the right place, as shown in the following code:
# config-pin overlay BB-UART4 # cat /sys/devices/bone_capemgr.*/slots
- Now, reboot your BBB and check whether the device is present in the device list by using the following command:
$ ls -l /dev/ttyO* crw-rw---- 1 root tty 247, 0 Mar 1 20:46 /dev/ttyO0 crw-rw---T 1 root dialout 247, 4 Jul 13 02:12 /dev/ttyO4
- Finally, check whether it is loading properly with the following command:
$ dmesg
This is how the output should look:
[ 188.335168] bone-capemgr bone_capemgr.9: part_number 'BB-UART4', version 'N/A' [ 188.335235] bone-capemgr bone_capemgr.9: slot #7: generic override [ 188.335250] bone-capemgr bone_capemgr.9: bone: Using override eeprom data at slot 7 [ 188.335266] bone-capemgr bone_capemgr.9: slot #7: 'Override Board Name,00A0,Override Manuf,BB-UART4' [ 188.335355] bone-capemgr bone_capemgr.9: slot #7: Requesting part number/version based 'BB-UART4-00A0.dtbo [ 188.335370] bone-capemgr bone_capemgr.9: slot #7: Requesting firmware 'BB-UART4-00A0.dtbo' for board-name 'Override Board Name', version '00A0' [ 188.335400] bone-capemgr bone_capemgr.9: slot #7: dtbo 'BB-UART4-00A0.dtbo' loaded; converting to live tree [ 188.335673] bone-capemgr bone_capemgr.9: slot #7: #2 overlays [ 188.343353] 481a8000.serial: ttyO4 at MMIO 0x481a8000 (irq = 45) is a OMAP UART4 [ 188.343792] bone-capemgr bone_capemgr.9: slot #7: Applied #2 overlays.
Note
Tips to get a GPS Fix
Your best method to get the GPS module connected is to take it outdoors. However, as this is not a likely option when you develop a project, putting it against or even just outside a window will often suffice. If it is cloudy, and if you don't have a reasonably clear sky view from your module's antenna, do not expect a quick connection. Be patient. When a fix is made, the flashing LED will cycle very slowly at about 15-second intervals.
Even if GPS modules do not have a fix, be aware that they will still send data. This can be confusing because you may run some of the following commands and think that your connection is fine, but you just keep getting junk (blank) data. However, to reiterate, the flashing LED needs to have slowed down to 15-second intervals to verify that you have a fix.
- Although the output is not pretty, the following command is a useful first step in making sure that your devices are hooked up because it will show the raw NMEA data coming out of the GPS:
$ cat /dev/ttyO4
Note
NMEA - The National Marine Electronics Associations' GPS language protocol standard.
- Verify that your wiring is correct and that the module is generating data properly (irrespective of a satellite fix) as follows:
$ sudo screen /dev/ttyO4 9600
The output should immediately begin and look something similar to this:
$GPGGA,163356.000,4044.0318,N,07400.1854,W,1,5,2.65,4.0,M,-34.2,M,,*67 $GPGSA,A,3,13,06,10,26,02,,,,,,,,2.82,2.65,0.95*04 $GPRMC,163356.000,A,4044.0318,N,07400.1854,W,2.05,68.70,031214,,,A*46 $GPVTG,68.70,T,,M,2.05,N,3.81,K,A*09 $GPGGA,163357.000,4044.0322,N,07400.1853,W,1,5,2.65,3.7,M,-34.2,M,,*68 $GPGSA,A,3,13,06,10,26,02,,,,,,,,
- Now, quit the program using one of the the following methods:
Ctrl + a, enter or copy and paste
:quit
with the colon to the highlighted box at the bottom, or press Ctrl + a + k + y.
Installing the GPS toolset
- The next set of ingredients in the recipe consists of installing and testing a common toolset to parse GPS on Linux. As always, before installing something new, it is good practice to update your repos with the following command:
$ sudo apt-get update
- Install the tools, including
gpsd
, a service daemon to monitor your GPS receiver. The package exposes all the data on location, course, and velocity on the TCP port 2947 of your BBB and efficiently parses the NMEA text that pours out of the GPS receiver, as shown in the following command:$ sudo apt-get install gpsd gpsd-clients python-gps
For the preceding code,
gpsd-clients
installs some test clients, andpython-gps
installs the required Python library to communicate withgpsd
via Python scripts.Note
After the installation, you may find it useful to run
man gpsd
and review the package's well-written and informative manual. It not only provides the details around what you just installed, but it also provides the general GPS-related content. - If the planets or communication satellites are aligned, you can run this command from the newly installed toolset and begin to display the GPS data:
$ sudo gpsmon /dev/ttyO4
You should see a terminal GUI that looks similar to the following screenshot:
- To quit, press Ctrl + C or enter
q
and then return (Enter) key. - Now, we will test the other principal tool that you just installed with the following command:
$ sudo cgps -s
The output includes the current date and time in UTC, the latitude and longitude, and the approximate altitude.
Troubleshooting—Part 1
You may run into problems here. Commonly, on a first time set up and running, cgps
may time out, close by itself, and lead you to believe that there is a problem with your setup. If so, the next steps can lead you back on the path to GPS nirvana:
- We will begin by stopping all the running instances of GPS, as shown in the following code:
$ sudo killall gpsd
- Now, let's get rid of any sockets that the
gpsd
commands may have left behind with the following command:$ sudo rm /var/run/gpsd.sock
There is a systemd bug that we will typically need to address.
- Open the systemd GPSD service using the following command:
$ sudo nano /lib/systemd/system/gpsd.service
- Paste this command to the window with the following script:
[Unit] Description=GPS (Global Positioning System) Daemon Requires=gpsd.socket [Service] ExecStart=/usr/sbin/gpsd -n -N /dev/ttyO4 [Install] Also=gpsd.socket
- Then, restart the systemd service as follows:
$ sudo service gpsd start
- You should now be able run either of the following services again:
$ sudo gpsmon /dev/ttyO4
Alternatively, you can run the following command:
$ sudo cgps -s
Troubleshooting—Part 2
Sometimes, the preceding fixes don't fix it. Here are several more suggestions for troubleshooting purposes:
- Set up a control socket for GPS with the following command:
$ sudo gpsd -N -D3 -F /var/run/gpsd.sock
Note
The explanation of the command-line flags or options are as follows:
-N
: This tellsgpsd
to immediately post the GPS data. Although this is useful for testing purposes, it can also drain power, so leave it off if your use case is battery-powered.-F
: This creates a control socket for device addition and removal. The option requires a valid pathname on your local filesystem, which is why our command is appended with/var/run/gpsd.sock
.
- We may also need to install a package that lets us examine any port conflict that could be occurring, as shown in the following command:
$ sudo apt-get install lsof
- This installed utility will open and display the system files, including disk files, named pipes, network sockets, and devices opened by all the processes. There are multiple uses for the tool. However, we only want to determine whether the GPS module is speaking correctly to the port
2947
and if there are any conflicts. So, we will run the following command:$ sudo lsof -i :2947
This is how the output should look:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd 1 root 24u IPv4 6907 0t0 TCP localhost:gpsd (LISTEN) gpsd 5960 nobody 4u IPv4 6907 0t0 TCP localhost:gpsd (LISTEN)
- You may also want to check whether any instances of the GPS are running and then kill them with the following command:
$ ps aux |grep gps $ sudo killall gpsd
For a final bit of cooking with the GPS board, we want to run a Python script and display the data in tidy, parsed output. The code was originally written for the RPi, but it is useable on the BBB as well.
- Go get it with the following command:
$ git clone https://github.com/HudsonWerks/gps-tests.git
- Now, browse to the new directory that we just created and take a look at the file that we will use with the following code:
$ cd gps-tests $ sudo nano GPStest1.py
- Let's peruse the script a bit to understand some of its key parts:
The script requires a number of Python libraries:
import os from gps import * from time import * import time import threading
Keep in mind that getting a fix and then obtaining a good GPS data can take several moments before the system settles into a comfortable flow, as shown in the following code:
#It may take a second or two to get good data #print gpsd.fix.latitude,', ',gpsd.fix.longitude,' Time: ',gpsd.utc
If you find the output overwhelming, you can always modify the print commands to simplify the display as follows:
print print ' GPS reading' print '----------------------------------------' print 'latitude ' , gpsd.fix.latitude print 'longitude ' , gpsd.fix.longitude print 'time utc ' , gpsd.utc,' + ', gpsd.fix.time print 'altitude (m)' , gpsd.fix.altitude print 'eps ' , gpsd.fix.eps print 'epx ' , gpsd.fix.epx print 'epv ' , gpsd.fix.epv print 'ept ' , gpsd.fix.ept print 'speed (m/s) ' , gpsd.fix.speed print 'climb ' , gpsd.fix.climb print 'track ' , gpsd.fix.track print 'mode ' , gpsd.fix.mode print print 'sats ' , gpsd.satellites time.sleep(5)
- Now close the script and run the following command:
$ python GPStest1.py
In a few seconds, the nicely formatted GPS data will be displayed in your terminal window.
There's more...
- Sparkfun's tutorial on GPS is definitely worth the read at https://learn.sparkfun.com/tutorials/gps-basics/all
- For further GPSD troubleshooting, refer to http://www.catb.org/gpsd/troubleshooting.html
How to do it…
For the GPS setup, the steps are as follows:
- Insert the PCB pins into the breadboard and wire the pins according to the following fritzing diagram:
P9_11 (blue wire): This denotes RX on BBB and TX on GPS PCB. At first, it may seem confusing to not wire TX to TX, and so on. However, once you understand the pin's function, the logic is clear: a transmit (TX) pin pairs with a pin that can receive data (RX), whereas a receive pin pairs with a pin that transmits data.
P9_13 (green wire): This specifies TX on BBB and RX on GPS PCB
P9_1: This indicates GND
P9_3: This specifies 3.3V
- Now, carefully attach the antenna to the board's uFL connector.
- Next, power your BBB. Here's where it gets a bit tricky.
When your BBB starts, you will immediately see the Fix button on the GPS board that will begin to flash quickly, approximately 1x per second. We will come back to check the integrity of the module's satellite connection in a later step.
- In order to gain access to the UART pins on the BBB, we have to enable them using a Device Tree overlay. Until recently, this was a multistep process. However, now that the BeagleBone Universal I/O package comes preloaded on the current versions of the firmware, enabling the pins (in the case, UART4) in a snap. Let's begin by logging in as root with the following command:
$ sudo -i
- Then, run the relevant Universal I/O command and check whether it went to the right place, as shown in the following code:
# config-pin overlay BB-UART4 # cat /sys/devices/bone_capemgr.*/slots
- Now, reboot your BBB and check whether the device is present in the device list by using the following command:
$ ls -l /dev/ttyO* crw-rw---- 1 root tty 247, 0 Mar 1 20:46 /dev/ttyO0 crw-rw---T 1 root dialout 247, 4 Jul 13 02:12 /dev/ttyO4
- Finally, check whether it is loading properly with the following command:
$ dmesg
This is how the output should look:
[ 188.335168] bone-capemgr bone_capemgr.9: part_number 'BB-UART4', version 'N/A' [ 188.335235] bone-capemgr bone_capemgr.9: slot #7: generic override [ 188.335250] bone-capemgr bone_capemgr.9: bone: Using override eeprom data at slot 7 [ 188.335266] bone-capemgr bone_capemgr.9: slot #7: 'Override Board Name,00A0,Override Manuf,BB-UART4' [ 188.335355] bone-capemgr bone_capemgr.9: slot #7: Requesting part number/version based 'BB-UART4-00A0.dtbo [ 188.335370] bone-capemgr bone_capemgr.9: slot #7: Requesting firmware 'BB-UART4-00A0.dtbo' for board-name 'Override Board Name', version '00A0' [ 188.335400] bone-capemgr bone_capemgr.9: slot #7: dtbo 'BB-UART4-00A0.dtbo' loaded; converting to live tree [ 188.335673] bone-capemgr bone_capemgr.9: slot #7: #2 overlays [ 188.343353] 481a8000.serial: ttyO4 at MMIO 0x481a8000 (irq = 45) is a OMAP UART4 [ 188.343792] bone-capemgr bone_capemgr.9: slot #7: Applied #2 overlays.
Note
Tips to get a GPS Fix
Your best method to get the GPS module connected is to take it outdoors. However, as this is not a likely option when you develop a project, putting it against or even just outside a window will often suffice. If it is cloudy, and if you don't have a reasonably clear sky view from your module's antenna, do not expect a quick connection. Be patient. When a fix is made, the flashing LED will cycle very slowly at about 15-second intervals.
Even if GPS modules do not have a fix, be aware that they will still send data. This can be confusing because you may run some of the following commands and think that your connection is fine, but you just keep getting junk (blank) data. However, to reiterate, the flashing LED needs to have slowed down to 15-second intervals to verify that you have a fix.
- Although the output is not pretty, the following command is a useful first step in making sure that your devices are hooked up because it will show the raw NMEA data coming out of the GPS:
$ cat /dev/ttyO4
Note
NMEA - The National Marine Electronics Associations' GPS language protocol standard.
- Verify that your wiring is correct and that the module is generating data properly (irrespective of a satellite fix) as follows:
$ sudo screen /dev/ttyO4 9600
The output should immediately begin and look something similar to this:
$GPGGA,163356.000,4044.0318,N,07400.1854,W,1,5,2.65,4.0,M,-34.2,M,,*67 $GPGSA,A,3,13,06,10,26,02,,,,,,,,2.82,2.65,0.95*04 $GPRMC,163356.000,A,4044.0318,N,07400.1854,W,2.05,68.70,031214,,,A*46 $GPVTG,68.70,T,,M,2.05,N,3.81,K,A*09 $GPGGA,163357.000,4044.0322,N,07400.1853,W,1,5,2.65,3.7,M,-34.2,M,,*68 $GPGSA,A,3,13,06,10,26,02,,,,,,,,
- Now, quit the program using one of the the following methods:
Ctrl + a, enter or copy and paste
:quit
with the colon to the highlighted box at the bottom, or press Ctrl + a + k + y.
Installing the GPS toolset
- The next set of ingredients in the recipe consists of installing and testing a common toolset to parse GPS on Linux. As always, before installing something new, it is good practice to update your repos with the following command:
$ sudo apt-get update
- Install the tools, including
gpsd
, a service daemon to monitor your GPS receiver. The package exposes all the data on location, course, and velocity on the TCP port 2947 of your BBB and efficiently parses the NMEA text that pours out of the GPS receiver, as shown in the following command:$ sudo apt-get install gpsd gpsd-clients python-gps
For the preceding code,
gpsd-clients
installs some test clients, andpython-gps
installs the required Python library to communicate withgpsd
via Python scripts.Note
After the installation, you may find it useful to run
man gpsd
and review the package's well-written and informative manual. It not only provides the details around what you just installed, but it also provides the general GPS-related content. - If the planets or communication satellites are aligned, you can run this command from the newly installed toolset and begin to display the GPS data:
$ sudo gpsmon /dev/ttyO4
You should see a terminal GUI that looks similar to the following screenshot:
- To quit, press Ctrl + C or enter
q
and then return (Enter) key. - Now, we will test the other principal tool that you just installed with the following command:
$ sudo cgps -s
The output includes the current date and time in UTC, the latitude and longitude, and the approximate altitude.
Troubleshooting—Part 1
You may run into problems here. Commonly, on a first time set up and running, cgps
may time out, close by itself, and lead you to believe that there is a problem with your setup. If so, the next steps can lead you back on the path to GPS nirvana:
- We will begin by stopping all the running instances of GPS, as shown in the following code:
$ sudo killall gpsd
- Now, let's get rid of any sockets that the
gpsd
commands may have left behind with the following command:$ sudo rm /var/run/gpsd.sock
There is a systemd bug that we will typically need to address.
- Open the systemd GPSD service using the following command:
$ sudo nano /lib/systemd/system/gpsd.service
- Paste this command to the window with the following script:
[Unit] Description=GPS (Global Positioning System) Daemon Requires=gpsd.socket [Service] ExecStart=/usr/sbin/gpsd -n -N /dev/ttyO4 [Install] Also=gpsd.socket
- Then, restart the systemd service as follows:
$ sudo service gpsd start
- You should now be able run either of the following services again:
$ sudo gpsmon /dev/ttyO4
Alternatively, you can run the following command:
$ sudo cgps -s
Troubleshooting—Part 2
Sometimes, the preceding fixes don't fix it. Here are several more suggestions for troubleshooting purposes:
- Set up a control socket for GPS with the following command:
$ sudo gpsd -N -D3 -F /var/run/gpsd.sock
Note
The explanation of the command-line flags or options are as follows:
-N
: This tellsgpsd
to immediately post the GPS data. Although this is useful for testing purposes, it can also drain power, so leave it off if your use case is battery-powered.-F
: This creates a control socket for device addition and removal. The option requires a valid pathname on your local filesystem, which is why our command is appended with/var/run/gpsd.sock
.
- We may also need to install a package that lets us examine any port conflict that could be occurring, as shown in the following command:
$ sudo apt-get install lsof
- This installed utility will open and display the system files, including disk files, named pipes, network sockets, and devices opened by all the processes. There are multiple uses for the tool. However, we only want to determine whether the GPS module is speaking correctly to the port
2947
and if there are any conflicts. So, we will run the following command:$ sudo lsof -i :2947
This is how the output should look:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd 1 root 24u IPv4 6907 0t0 TCP localhost:gpsd (LISTEN) gpsd 5960 nobody 4u IPv4 6907 0t0 TCP localhost:gpsd (LISTEN)
- You may also want to check whether any instances of the GPS are running and then kill them with the following command:
$ ps aux |grep gps $ sudo killall gpsd
For a final bit of cooking with the GPS board, we want to run a Python script and display the data in tidy, parsed output. The code was originally written for the RPi, but it is useable on the BBB as well.
- Go get it with the following command:
$ git clone https://github.com/HudsonWerks/gps-tests.git
- Now, browse to the new directory that we just created and take a look at the file that we will use with the following code:
$ cd gps-tests $ sudo nano GPStest1.py
- Let's peruse the script a bit to understand some of its key parts:
The script requires a number of Python libraries:
import os from gps import * from time import * import time import threading
Keep in mind that getting a fix and then obtaining a good GPS data can take several moments before the system settles into a comfortable flow, as shown in the following code:
#It may take a second or two to get good data #print gpsd.fix.latitude,', ',gpsd.fix.longitude,' Time: ',gpsd.utc
If you find the output overwhelming, you can always modify the print commands to simplify the display as follows:
print print ' GPS reading' print '----------------------------------------' print 'latitude ' , gpsd.fix.latitude print 'longitude ' , gpsd.fix.longitude print 'time utc ' , gpsd.utc,' + ', gpsd.fix.time print 'altitude (m)' , gpsd.fix.altitude print 'eps ' , gpsd.fix.eps print 'epx ' , gpsd.fix.epx print 'epv ' , gpsd.fix.epv print 'ept ' , gpsd.fix.ept print 'speed (m/s) ' , gpsd.fix.speed print 'climb ' , gpsd.fix.climb print 'track ' , gpsd.fix.track print 'mode ' , gpsd.fix.mode print print 'sats ' , gpsd.satellites time.sleep(5)
- Now close the script and run the following command:
$ python GPStest1.py
In a few seconds, the nicely formatted GPS data will be displayed in your terminal window.
There's more...
- Sparkfun's tutorial on GPS is definitely worth the read at https://learn.sparkfun.com/tutorials/gps-basics/all
- For further GPSD troubleshooting, refer to http://www.catb.org/gpsd/troubleshooting.html
There's more...
- Sparkfun's tutorial on GPS is definitely worth the read at https://learn.sparkfun.com/tutorials/gps-basics/all
- For further GPSD troubleshooting, refer to http://www.catb.org/gpsd/troubleshooting.html
Location-based recipes – Bluetooth LE and Beacons
In the past, you may have had the opportunity to use Bluetooth devices in your projects. However, in all probability, that would have been an earlier version of BT, now commonly referred to as "classic" Bluetooth. Before we jump into an actual recipe on how to use these small radio devices, we should take a look at some of the significant differences between the classic version of Bluetooth and the Bluetooth Low Energy (BLE) spec because they are very different animals. Although they are both available as part of the 4.0 spec, we will work only with the BLE piece for our recipe.
Classic Bluetooth
With the classic version of the stack, one device basically connects to another device, data is exchanged serially, and the data does not persist. For example, when you set up a BT headset, the audio comes piping into your ears, and the data goes on after the throughput. Furthermore, the connection does not reveal or show anything about what's happening in the middle of that pipe with the data itself.
Bluetooth Low Energy
Although more challenging to work with and still nascent with its documentation, BLE (sometimes referred to as Bluetooth Smart) is a far more robust environment for managing data, particularly in the world of IoT. Several key elements distinguish it from its earlier kin:
- Central device versus peripheral device rubric: In a BLE ecosystem, there will be a broadcast (peripheral) device that sends out data and a (central) device or devices that reads from this broadcast. The device relationship is analogous to a community bulletin board with a bunch of readers or a client/server relationship. However, in BLE-land, the normal assumptions are flipped: the server is a very low-powered device, whereas the client is typically a more sophisticated device, such as a smartphone, a laptop, a tablet, or other wireless device.
- Not one-to-one: BLE allows multiple simultaneous connections to the same server or peripheral device.
- Low power: The connections between devices are very short in BLE. This results in extremely low power usage. Devices can operate with simple lithium coin cell batteries.
- Broad services and characteristics schema: The data presented by a peripheral is structured as services, which are then subdivided into characteristics. Services are akin to the notices on a bulletin board, whereas characteristics are similar to the individual paragraphs of these notices.
You can easily hook up to different services and characteristics with a few lines of code. For example, you can interact with a battery service and easily determine the power levels remaining for a device. Alternatively, your use case may be related to health or fitness, which means that you can leverage the onboard health service that includes a characteristic (such as heartbeat data).
Beacons and iBeacons
Where GPS leaves off, Beacons begin. This emerging BLE technology is quickly becoming the next big thing in location sensing. Although proven, powerful, and ubiquitous, GPS can only determine the coordinates of an object within 20-30 feet. However, the BLE Beacon technology is commonly referred to as hyperlocal in its sensitivity because it is accurate within a range of 100 meters down to inches. Thus far, most of the interest around the Beacon technology is focused on how marketers and advertisers want to use it in order to send you targeted offers… Yuck!
This is largely due to the fact that Apple's marketing-centric version of the protocol called iBeacons has been the most commonly referenced and easiest type to get running quickly. However, the intrinsic BLE Beacon stack, iBeacon or otherwise, is very exciting for several reasons:
- It delivers low cost radio signaling
- It provides fairly rapid and simple development requirements
- It requires very low power with its use of BLE
- It broadcasts far more precise location data than GPS
For IoT-like scenarios, both indoor and outdoor, Beacons provide much promise far beyond annoying marketing messages. Also, you can actually buy premade beacons for very little money, sometimes for only a few dollars (USD).
It may seem like overkill to be using a full-blown microcomputer, such as the BBB, to serve as a Beacon. However, our intention is to create our own BBB version so that we have more flexibility in understanding and building the constituent parts of a Beacon network. Doing this as an open source recipe allows you to pull the levers yourself.
A further point to clarify here is that BLE Beacons do not actually send content that a user receives on their smartphone app. The beacon simply provides the rudimentary data to a mobile app, which allows that app to determine its location in a venue or outdoor spot and in turn sends the user location-specific data. Alternatively, it can capture and make use of that data in other ways.
Furthermore, iBeacons do not track users based on any kind of profiling requirements; the interaction can be—and generally is—completely anonymous, so concerns about privacy are negligible.
With Beacons, there are several data fields that you typically want to watch. This helps in differentiating one beacon from another. For instance, let's say that we are in the Museum of Natural History in New York City that has a beacon network. Here are the relevant data fields:
- UUID: Services are identified by unique numbers known as UUIDs (Universal Unique Identifier), which you may be familiar with from other projects. Therefore, the museum would have its own unique UUID string.
- The major field (ID): Inputting a specific value in this field can specify a more general location, for example, a particular floor in the museum.
- The minor field (ID): Inputting a value in this field will specify a particular gallery on a specific floor.
- TX Power: This is used to try to estimate the distance based on the signal strength of the Wi-Fi connection (the RSSI value) in a particular room.
The major and minor IDs can be used to trigger certain behaviors in your application when it discovers one of your beacons. All of these fields come together to make pinpointing locations extremely accurate.
Getting ready
The BBB is powered up via USB and connected online either via Wi-Fi or Ethernet with two additional items:
- USB Bluetooth LE (BLE), also known as Bluetooth 4.0 adapter—we will use a Targus dongle (product ID ACB10US1). This uses the Broadcom BCM20702 chipset. There are far cheaper ones that should work fine on the BBB that cost around USD $10.00-15.00. Here is a list of compatible Bluetooth dongles for the Raspberry Pi (http://elinux.org/RPi_USB_Bluetooth_adapters). Many of those listed will likely work with the BBB, although they have not all been tested for compatibility.
- Smartphone with Bluetooth LE—iPhones starting from 4S to any of the current models are BLE-compliant. On the Android side, there are exceptions. By default, the current models of an Android phone runs on 4.3 or higher BLE. However, any Android phones that cannot run on version 4.3 or higher will not work with this set of recipes.
How to do it…
Part 1—Setting up your smartphone
As mentioned earlier in the chapter, we need to install some apps on our smartphone in order to make this recipe meaningful and demonstrate the BBB's beacon-ness.
For the iPhone, we installed and tested two different free apps from the App Store, one is called Locate (by Radius Networks) and the other is called Beacon Tool. (The developers must gotten up very early in the morning to come up with those names…).
Locate has a few more functionalities than Beacon Tool because it lets us set the major and minor values for the Beacon.
Part 2—Setting up a simple IoT test environment
You can test and track the iBeacon using a web service. There are several businesses in this space. We used a platform called EvoThings, which is a free, open source platform.
Evothings allows you to use a simple IDE on your desktop and then demonstrate an iBeacon app on a smartphone with a Beacon-enabled BBB in the middle of the mix. Perform the following steps:
- Download and install Evothings Studio (http://evothings.com/). The installation requires a Workbench desktop and a mobile app, all of which is explained on their website.
- After downloading Evothings Studio, you will find a Mac OS X and a Windows version on the desktop. Install your preferred client.
- For the mobile app, install and start the Evothings client app on your mobile device. Android and iOS are available at their respective online stores.
There are numerous demos and examples that come with Evothings. Although they tend to be focused on how to use an Arduino as a beacon, the code is very flexible (and open source), so everything is customizable for other platforms. For our first quick example, in your desktop Evothings Workbench, open the following file in a text editor:
Evothings_Studio/examples/ibeacon-scan/index.js
Then, scan about halfway down the page to find the following code:
// Add your own manufacturer UUIDs to this list. {uuid:'B9407F30-F5F8-466E-AFF9-25556B57FE6D'}, {uuid:'F7826DA6-4FA2-4E98-8024-BC5B71E0893E'}, {uuid:'8DEEFBB9-F738-4297-8040-96668BB44281'}, {uuid:'A0B13730-3A9A-11E3-AA6E-0800200C9A66'},
Now, add your generated UUID from the earlier step to line up with the following syntax:
{uuid:'3784B5B0-2DA7-11E4-8C21-0800200C9A66'},
Note
Other than their own identity, iBeacons do not push notifications to the central (receiving) devices. However, a mobile app on your phone can use signals received from iBeacons to trigger their own push notifications.
Part 3: Setting up the BBB
Let's start with the essential package on how to control and interact with Bluetooth devices (LE or otherwise) and the Linux Bluetooth stack BlueZ. On the current Debian distro that comes with any newly purchased BBB, BlueZ should be already installed. Perform the following steps:
- First, update and upgrade the BBB with the following command:
$ sudo apt-get update
- Then, we will verify that BlueZ is installed using the following command:
$ bluetoothd -v
If you see a version number appear, skip to step 4; otherwise, proceed to the next step.
- Now, install BlueZ with the following command:
$ sudo apt-get install bluez
Note
You may want to install BlueZ from its source. Here is the code for it:
sudo mkdir bluez cd bluez sudo wget www.kernel.org/pub/linux/bluetooth/bluez-x.xx.tar.xz
Check for the current version of BlueZ before running
wget
. - Then, connect the dongle to the USB port and verify that it is recognized with the following command:
$ lsusb
- Now, we want to set up Bluetooth communications between the BBB and any other BLE devices that require using a series of BlueZ commands. To do this, we will use the
hciconfig
tool and begin by taking a look at the address of the USB adapter as follows:$ hcitool dev Devices: hci0 00:19:0E:15:DE:87
- The preceding output shows one device present with the ID
0
that is prepended withhci
; this is part of the protocol's naming convention. We will take this ID and append it to the command, include the (-a
) option to output information about all the devices present, and check the dongle's ready state, as shown in the following code:$ hciconfig -a hci0
Your screen should show the following code:
hci0: Type: BR/EDR Bus: USB BD Address: 00:19:0E:15:DE:87 ACL MTU: 1021:8 SCO MTU: 64:1 DOWN RX bytes:1267 acl:0 sco:0 events:47 errors:0 TX bytes:747 acl:0 sco:0 commands:47 errors:0 Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87 Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3 Link policy: RSWITCH SNIFF Link mode: SLAVE ACCEPT
- Ensure that it says
DOWN
, which is not what we want. So, up, up, and away we go:$ sudo hciconfig hci0 up
- Then, verify that the command worked by repeating our earlier step. Your
stdout
should look similar to the following command:$ hciconfig -a hci0 hci0: Type: BR/EDR Bus: USB BD Address: 00:19:0E:15:DE:87 ACL MTU: 1021:8 SCO MTU: 64:1 UP RUNNING RX bytes:990 acl:0 sco:0 events:44 errors:0 TX bytes:738 acl:0 sco:0 commands:44 errors:0 Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87 Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3 Link policy: RSWITCH SNIFF Link mode: SLAVE ACCEPT Name: 'BCM20702A' Class: 0x000000 Service Classes: Unspecified Device Class: Miscellaneous, HCI Version: 4.0 (0x6) Revision: 0x1000 LMP Version: 4.0 (0x6) Subversion: 0x220e Manufacturer: Broadcom Corporation (15)
- Now, we will set up the dongle to begin what is known as advertising in the BLE parlance. We will perform this in the low energy (
le
) mode using the flag3
; this sets the connection mode:$ sudo hciconfig hci0 leadv 3
Note
A further word about nomenclature in the iBeacon/BLE landscape is that you will often see references to the word advertising when you develop with BLE. The term is used generically to refer to a packet of data that is being sent from a BT device to make its presence known; it has nothing to do with Apple's original advertising/marketing-centric purposes for iBeacon.
- By default, the BLE dongle will scan for other devices. However, we want to turn this function off because it can interfere with advertising as follows:
$ sudo hciconfig hci0 noscan
- The last command adds the UUID, as shown in the following command:
$ sudo hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 37 84 B5 B0 2D A7 11 E4 8C 21 08 00 20 0C 9A 66 00 00 00 00 C8
The instant you send the preceding command, you should see a notification/popup on your smartphone. With the iLocate app on the iPhone, it should say Entered region: BBB beacon 1.
(This assumes that a smartphone app is already installed and set up to recognize the BBB beacon UUID).
Congratulations! You are now able to broadcast hyperlocal data without the need for a big GPS satellite.
There's more...
The following references provide more detail on BTLE:
- Classic versus BTLE discussion: This gives you an excellent drill-down into the nature of BLE's distinctiveness from Bluetooth Classic at http://makezine.com/2014/06/16/the-bluetooth-le-doc-a-thon-at-itp-camp/
- BTLE documentation: This provides various examples from a Doc-a-thon at https://github.com/tigoe/BLEDocs/wiki
- Estimote teardown: Make magazine takes apart an Estimote iBeacon, a commercial, mostly closed product at http://makezine.com/2014/01/03/reverse-engineering-the-estimote/
- Tile: Information on this new, very cheap, and small Beacon can be found at http://tiletogether.tumblr.com/post/98897004442/tile-is-coming-to-android#notes
- Troubleshoot your Bluetooth installation (https://wiki.archlinux.org/index.php/bluetooth)
- Bubble app: This app that strives to simplify the process of setting up and interacting with iBeacon content by using tags to connect websites to things in the real world. Learn more at http://discoverbubble.com/
Getting ready
The BBB is powered up via USB and connected online either via Wi-Fi or Ethernet with two additional items:
- USB Bluetooth LE (BLE), also known as Bluetooth 4.0 adapter—we will use a Targus dongle (product ID ACB10US1). This uses the Broadcom BCM20702 chipset. There are far cheaper ones that should work fine on the BBB that cost around USD $10.00-15.00. Here is a list of compatible Bluetooth dongles for the Raspberry Pi (http://elinux.org/RPi_USB_Bluetooth_adapters). Many of those listed will likely work with the BBB, although they have not all been tested for compatibility.
- Smartphone with Bluetooth LE—iPhones starting from 4S to any of the current models are BLE-compliant. On the Android side, there are exceptions. By default, the current models of an Android phone runs on 4.3 or higher BLE. However, any Android phones that cannot run on version 4.3 or higher will not work with this set of recipes.
How to do it…
Part 1—Setting up your smartphone
As mentioned earlier in the chapter, we need to install some apps on our smartphone in order to make this recipe meaningful and demonstrate the BBB's beacon-ness.
For the iPhone, we installed and tested two different free apps from the App Store, one is called Locate (by Radius Networks) and the other is called Beacon Tool. (The developers must gotten up very early in the morning to come up with those names…).
Locate has a few more functionalities than Beacon Tool because it lets us set the major and minor values for the Beacon.
Part 2—Setting up a simple IoT test environment
You can test and track the iBeacon using a web service. There are several businesses in this space. We used a platform called EvoThings, which is a free, open source platform.
Evothings allows you to use a simple IDE on your desktop and then demonstrate an iBeacon app on a smartphone with a Beacon-enabled BBB in the middle of the mix. Perform the following steps:
- Download and install Evothings Studio (http://evothings.com/). The installation requires a Workbench desktop and a mobile app, all of which is explained on their website.
- After downloading Evothings Studio, you will find a Mac OS X and a Windows version on the desktop. Install your preferred client.
- For the mobile app, install and start the Evothings client app on your mobile device. Android and iOS are available at their respective online stores.
There are numerous demos and examples that come with Evothings. Although they tend to be focused on how to use an Arduino as a beacon, the code is very flexible (and open source), so everything is customizable for other platforms. For our first quick example, in your desktop Evothings Workbench, open the following file in a text editor:
Evothings_Studio/examples/ibeacon-scan/index.js
Then, scan about halfway down the page to find the following code:
// Add your own manufacturer UUIDs to this list. {uuid:'B9407F30-F5F8-466E-AFF9-25556B57FE6D'}, {uuid:'F7826DA6-4FA2-4E98-8024-BC5B71E0893E'}, {uuid:'8DEEFBB9-F738-4297-8040-96668BB44281'}, {uuid:'A0B13730-3A9A-11E3-AA6E-0800200C9A66'},
Now, add your generated UUID from the earlier step to line up with the following syntax:
{uuid:'3784B5B0-2DA7-11E4-8C21-0800200C9A66'},
Note
Other than their own identity, iBeacons do not push notifications to the central (receiving) devices. However, a mobile app on your phone can use signals received from iBeacons to trigger their own push notifications.
Part 3: Setting up the BBB
Let's start with the essential package on how to control and interact with Bluetooth devices (LE or otherwise) and the Linux Bluetooth stack BlueZ. On the current Debian distro that comes with any newly purchased BBB, BlueZ should be already installed. Perform the following steps:
- First, update and upgrade the BBB with the following command:
$ sudo apt-get update
- Then, we will verify that BlueZ is installed using the following command:
$ bluetoothd -v
If you see a version number appear, skip to step 4; otherwise, proceed to the next step.
- Now, install BlueZ with the following command:
$ sudo apt-get install bluez
Note
You may want to install BlueZ from its source. Here is the code for it:
sudo mkdir bluez cd bluez sudo wget www.kernel.org/pub/linux/bluetooth/bluez-x.xx.tar.xz
Check for the current version of BlueZ before running
wget
. - Then, connect the dongle to the USB port and verify that it is recognized with the following command:
$ lsusb
- Now, we want to set up Bluetooth communications between the BBB and any other BLE devices that require using a series of BlueZ commands. To do this, we will use the
hciconfig
tool and begin by taking a look at the address of the USB adapter as follows:$ hcitool dev Devices: hci0 00:19:0E:15:DE:87
- The preceding output shows one device present with the ID
0
that is prepended withhci
; this is part of the protocol's naming convention. We will take this ID and append it to the command, include the (-a
) option to output information about all the devices present, and check the dongle's ready state, as shown in the following code:$ hciconfig -a hci0
Your screen should show the following code:
hci0: Type: BR/EDR Bus: USB BD Address: 00:19:0E:15:DE:87 ACL MTU: 1021:8 SCO MTU: 64:1 DOWN RX bytes:1267 acl:0 sco:0 events:47 errors:0 TX bytes:747 acl:0 sco:0 commands:47 errors:0 Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87 Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3 Link policy: RSWITCH SNIFF Link mode: SLAVE ACCEPT
- Ensure that it says
DOWN
, which is not what we want. So, up, up, and away we go:$ sudo hciconfig hci0 up
- Then, verify that the command worked by repeating our earlier step. Your
stdout
should look similar to the following command:$ hciconfig -a hci0 hci0: Type: BR/EDR Bus: USB BD Address: 00:19:0E:15:DE:87 ACL MTU: 1021:8 SCO MTU: 64:1 UP RUNNING RX bytes:990 acl:0 sco:0 events:44 errors:0 TX bytes:738 acl:0 sco:0 commands:44 errors:0 Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87 Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3 Link policy: RSWITCH SNIFF Link mode: SLAVE ACCEPT Name: 'BCM20702A' Class: 0x000000 Service Classes: Unspecified Device Class: Miscellaneous, HCI Version: 4.0 (0x6) Revision: 0x1000 LMP Version: 4.0 (0x6) Subversion: 0x220e Manufacturer: Broadcom Corporation (15)
- Now, we will set up the dongle to begin what is known as advertising in the BLE parlance. We will perform this in the low energy (
le
) mode using the flag3
; this sets the connection mode:$ sudo hciconfig hci0 leadv 3
Note
A further word about nomenclature in the iBeacon/BLE landscape is that you will often see references to the word advertising when you develop with BLE. The term is used generically to refer to a packet of data that is being sent from a BT device to make its presence known; it has nothing to do with Apple's original advertising/marketing-centric purposes for iBeacon.
- By default, the BLE dongle will scan for other devices. However, we want to turn this function off because it can interfere with advertising as follows:
$ sudo hciconfig hci0 noscan
- The last command adds the UUID, as shown in the following command:
$ sudo hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 37 84 B5 B0 2D A7 11 E4 8C 21 08 00 20 0C 9A 66 00 00 00 00 C8
The instant you send the preceding command, you should see a notification/popup on your smartphone. With the iLocate app on the iPhone, it should say Entered region: BBB beacon 1.
(This assumes that a smartphone app is already installed and set up to recognize the BBB beacon UUID).
Congratulations! You are now able to broadcast hyperlocal data without the need for a big GPS satellite.
There's more...
The following references provide more detail on BTLE:
- Classic versus BTLE discussion: This gives you an excellent drill-down into the nature of BLE's distinctiveness from Bluetooth Classic at http://makezine.com/2014/06/16/the-bluetooth-le-doc-a-thon-at-itp-camp/
- BTLE documentation: This provides various examples from a Doc-a-thon at https://github.com/tigoe/BLEDocs/wiki
- Estimote teardown: Make magazine takes apart an Estimote iBeacon, a commercial, mostly closed product at http://makezine.com/2014/01/03/reverse-engineering-the-estimote/
- Tile: Information on this new, very cheap, and small Beacon can be found at http://tiletogether.tumblr.com/post/98897004442/tile-is-coming-to-android#notes
- Troubleshoot your Bluetooth installation (https://wiki.archlinux.org/index.php/bluetooth)
- Bubble app: This app that strives to simplify the process of setting up and interacting with iBeacon content by using tags to connect websites to things in the real world. Learn more at http://discoverbubble.com/
How to do it…
Part 1—Setting up your smartphone
As mentioned earlier in the chapter, we need to install some apps on our smartphone in order to make this recipe meaningful and demonstrate the BBB's beacon-ness.
For the iPhone, we installed and tested two different free apps from the App Store, one is called Locate (by Radius Networks) and the other is called Beacon Tool. (The developers must gotten up very early in the morning to come up with those names…).
Locate has a few more functionalities than Beacon Tool because it lets us set the major and minor values for the Beacon.
Part 2—Setting up a simple IoT test environment
You can test and track the iBeacon using a web service. There are several businesses in this space. We used a platform called EvoThings, which is a free, open source platform.
Evothings allows you to use a simple IDE on your desktop and then demonstrate an iBeacon app on a smartphone with a Beacon-enabled BBB in the middle of the mix. Perform the following steps:
- Download and install Evothings Studio (http://evothings.com/). The installation requires a Workbench desktop and a mobile app, all of which is explained on their website.
- After downloading Evothings Studio, you will find a Mac OS X and a Windows version on the desktop. Install your preferred client.
- For the mobile app, install and start the Evothings client app on your mobile device. Android and iOS are available at their respective online stores.
There are numerous demos and examples that come with Evothings. Although they tend to be focused on how to use an Arduino as a beacon, the code is very flexible (and open source), so everything is customizable for other platforms. For our first quick example, in your desktop Evothings Workbench, open the following file in a text editor:
Evothings_Studio/examples/ibeacon-scan/index.js
Then, scan about halfway down the page to find the following code:
// Add your own manufacturer UUIDs to this list. {uuid:'B9407F30-F5F8-466E-AFF9-25556B57FE6D'}, {uuid:'F7826DA6-4FA2-4E98-8024-BC5B71E0893E'}, {uuid:'8DEEFBB9-F738-4297-8040-96668BB44281'}, {uuid:'A0B13730-3A9A-11E3-AA6E-0800200C9A66'},
Now, add your generated UUID from the earlier step to line up with the following syntax:
{uuid:'3784B5B0-2DA7-11E4-8C21-0800200C9A66'},
Note
Other than their own identity, iBeacons do not push notifications to the central (receiving) devices. However, a mobile app on your phone can use signals received from iBeacons to trigger their own push notifications.
Part 3: Setting up the BBB
Let's start with the essential package on how to control and interact with Bluetooth devices (LE or otherwise) and the Linux Bluetooth stack BlueZ. On the current Debian distro that comes with any newly purchased BBB, BlueZ should be already installed. Perform the following steps:
- First, update and upgrade the BBB with the following command:
$ sudo apt-get update
- Then, we will verify that BlueZ is installed using the following command:
$ bluetoothd -v
If you see a version number appear, skip to step 4; otherwise, proceed to the next step.
- Now, install BlueZ with the following command:
$ sudo apt-get install bluez
Note
You may want to install BlueZ from its source. Here is the code for it:
sudo mkdir bluez cd bluez sudo wget www.kernel.org/pub/linux/bluetooth/bluez-x.xx.tar.xz
Check for the current version of BlueZ before running
wget
. - Then, connect the dongle to the USB port and verify that it is recognized with the following command:
$ lsusb
- Now, we want to set up Bluetooth communications between the BBB and any other BLE devices that require using a series of BlueZ commands. To do this, we will use the
hciconfig
tool and begin by taking a look at the address of the USB adapter as follows:$ hcitool dev Devices: hci0 00:19:0E:15:DE:87
- The preceding output shows one device present with the ID
0
that is prepended withhci
; this is part of the protocol's naming convention. We will take this ID and append it to the command, include the (-a
) option to output information about all the devices present, and check the dongle's ready state, as shown in the following code:$ hciconfig -a hci0
Your screen should show the following code:
hci0: Type: BR/EDR Bus: USB BD Address: 00:19:0E:15:DE:87 ACL MTU: 1021:8 SCO MTU: 64:1 DOWN RX bytes:1267 acl:0 sco:0 events:47 errors:0 TX bytes:747 acl:0 sco:0 commands:47 errors:0 Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87 Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3 Link policy: RSWITCH SNIFF Link mode: SLAVE ACCEPT
- Ensure that it says
DOWN
, which is not what we want. So, up, up, and away we go:$ sudo hciconfig hci0 up
- Then, verify that the command worked by repeating our earlier step. Your
stdout
should look similar to the following command:$ hciconfig -a hci0 hci0: Type: BR/EDR Bus: USB BD Address: 00:19:0E:15:DE:87 ACL MTU: 1021:8 SCO MTU: 64:1 UP RUNNING RX bytes:990 acl:0 sco:0 events:44 errors:0 TX bytes:738 acl:0 sco:0 commands:44 errors:0 Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87 Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3 Link policy: RSWITCH SNIFF Link mode: SLAVE ACCEPT Name: 'BCM20702A' Class: 0x000000 Service Classes: Unspecified Device Class: Miscellaneous, HCI Version: 4.0 (0x6) Revision: 0x1000 LMP Version: 4.0 (0x6) Subversion: 0x220e Manufacturer: Broadcom Corporation (15)
- Now, we will set up the dongle to begin what is known as advertising in the BLE parlance. We will perform this in the low energy (
le
) mode using the flag3
; this sets the connection mode:$ sudo hciconfig hci0 leadv 3
Note
A further word about nomenclature in the iBeacon/BLE landscape is that you will often see references to the word advertising when you develop with BLE. The term is used generically to refer to a packet of data that is being sent from a BT device to make its presence known; it has nothing to do with Apple's original advertising/marketing-centric purposes for iBeacon.
- By default, the BLE dongle will scan for other devices. However, we want to turn this function off because it can interfere with advertising as follows:
$ sudo hciconfig hci0 noscan
- The last command adds the UUID, as shown in the following command:
$ sudo hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 37 84 B5 B0 2D A7 11 E4 8C 21 08 00 20 0C 9A 66 00 00 00 00 C8
The instant you send the preceding command, you should see a notification/popup on your smartphone. With the iLocate app on the iPhone, it should say Entered region: BBB beacon 1.
(This assumes that a smartphone app is already installed and set up to recognize the BBB beacon UUID).
Congratulations! You are now able to broadcast hyperlocal data without the need for a big GPS satellite.
There's more...
The following references provide more detail on BTLE:
- Classic versus BTLE discussion: This gives you an excellent drill-down into the nature of BLE's distinctiveness from Bluetooth Classic at http://makezine.com/2014/06/16/the-bluetooth-le-doc-a-thon-at-itp-camp/
- BTLE documentation: This provides various examples from a Doc-a-thon at https://github.com/tigoe/BLEDocs/wiki
- Estimote teardown: Make magazine takes apart an Estimote iBeacon, a commercial, mostly closed product at http://makezine.com/2014/01/03/reverse-engineering-the-estimote/
- Tile: Information on this new, very cheap, and small Beacon can be found at http://tiletogether.tumblr.com/post/98897004442/tile-is-coming-to-android#notes
- Troubleshoot your Bluetooth installation (https://wiki.archlinux.org/index.php/bluetooth)
- Bubble app: This app that strives to simplify the process of setting up and interacting with iBeacon content by using tags to connect websites to things in the real world. Learn more at http://discoverbubble.com/
There's more...
The following references provide more detail on BTLE:
- Classic versus BTLE discussion: This gives you an excellent drill-down into the nature of BLE's distinctiveness from Bluetooth Classic at http://makezine.com/2014/06/16/the-bluetooth-le-doc-a-thon-at-itp-camp/
- BTLE documentation: This provides various examples from a Doc-a-thon at https://github.com/tigoe/BLEDocs/wiki
- Estimote teardown: Make magazine takes apart an Estimote iBeacon, a commercial, mostly closed product at http://makezine.com/2014/01/03/reverse-engineering-the-estimote/
- Tile: Information on this new, very cheap, and small Beacon can be found at http://tiletogether.tumblr.com/post/98897004442/tile-is-coming-to-android#notes
- Troubleshoot your Bluetooth installation (https://wiki.archlinux.org/index.php/bluetooth)
- Bubble app: This app that strives to simplify the process of setting up and interacting with iBeacon content by using tags to connect websites to things in the real world. Learn more at http://discoverbubble.com/
Using sensors and data with ThingSpeak
Having some facility to hook up sensors is almost de rigueur when you talk about the Internet of Things. Furthermore, learning how to get your arms around the large datasets that typically pour out of these sensors has become a crucial piece of the IoT puzzle. In the next section, we will take a look at a recipe that introduces one method for managing this data.
We will be piggybacking on a recipe from Chapter 3, Physical Computing Recipes Using JavaScript, the BoneScript Library, and Python, and will use the TMP36 temperature sensor in particular. However, this time, you will learn how to use the data coming out of the sensor and display it in a more accessible IoT-style manner.
Getting ready
The following materials will be needed:
- BBB powered via 5V supply.
- Ethernet or Wi-Fi connectivity.
- Breadboard.
- 3x jumper wires.
- The TMP36 temperature sensor—this is the same sensor as the one we used in Chapter 3, Physical Computing Recipes Using JavaScript, the BoneScript Library, and Python. As a reminder, this low-cost sensor is readily available from numerous sources, including suppliers such as Sparkfun (https://www.sparkfun.com/products/10988).
How to do it…
Perform the following steps to use sensors and data with ThingSpeak:
- If BBB is not already off, turn it off.
- Using the following fritzing diagram, wire your powered down BBB:
You may remember this configuration from Chapter 3, Physical Computing Recipes Using JavaScript, the BoneScript Library, and Python as the wiring is exactly the same: GND uses the analog ground P9_34 (GNDA_ADC), 3V PWR at P9_3, and the sensor pin at P9_38.
- Power your BBB and log in via SSH.
- Sign up for a new account at ThingSpeak (https://thingspeak.com/), a free cloud service for data publishing and creating IoT-style products.
- Follow the prompts on the ThingSpeak site on how to set up a channel for your account. Just for fun, let's name the channel as
Ground Control Temperature
. - At the bottom of the same Channel Settings screen, create a second field called
Field Label 2
, as shown in the following screenshot: - You can now see the blank slate charts that have been created for the channel that will receive data from the BBB's sensor:
- From your GitHub repo, download the BoneScript (Node.js) code for this recipe to your BBB with the following command:
$ git clone https://github.com/HudsonWerks/tmp36-sensor-thingspeak.git
Note
The repo also includes a Python script example; however, we will only review the node version of the recipe here.
- Navigate to the new directory that we just created and open the Node.js file with the following command:
$ cd tmp36-sensor-thingspeak $ sudo nano tmp36-thingspeak.js
- In a browser on your client desktop, open the Cloud9 IDE and create a new JavaScript file. Then, copy and paste the code from the open
nano
window on your BBB to the Cloud9 file. - Before trying to send data to ThingSpeak, we should first verify that our sensor, wiring, and basic code are functioning properly. Now, in your Cloud9 window, click on the RUN button. If all goes well, the console output in the IDE should show readings similar to the following code:
debugger listening on port 15454 Sensor reading started. Output at 10-sec intervals. Temperature at Ground Control for Tue, 11 Aug 2015 19:20:21 GMT Fahrenheit: 64.4 Celsius: 18 _____________ Temperature at Ground Control for Tue, 11 Aug 2015 19:20:31 GMT Fahrenheit: 63.86 Celsius: 17.7
If you are not getting readings from the sensor, go back and check your wiring.
- Next, we will hook up our code to the ThingSpeak channel that we set up in the first part of this recipe using the generated API. Back on the ThingSpeak Channels tab, drill down to the new channel you created and search for the API Keys tab option. Select this tab and then copy (Ctrl + C) the Write API Key generated, as shown in the following screenshot:
- Back in the Cloud9 window, on line 30 of the
tmp36
code window, paste your ThingSpeak Write API key to the designated part of the code as follows://Post temperature data to ThingSpeak request.post('http://api.thingspeak.com:80/update',{form:{api_key: 'THINGSPEAK_WRITE_API_KEY_HERE', field1: temp_f, field2: temp_c}});
- Now, it's time to see your temperature readings that is displayed on the ThingSpeak cloud service. So, as you again click on RUN in the IDE, your Cloud9 console should be outputting temperature readings as before. Within a few moments, back on the ThingSpeak channel, data points should be appearing at 10-second intervals on the screen, plotting the fluctuations of Ground Control Temperature of your room, as shown in the following screenshot:
- Last but not least, we want to make the sensor data visible through yet another method, this time using Twitter. As Twitter is free and readily available on your smartphone, it serves as a useful channel to funnel IoT data. ThingSpeak simplifies the process considerably by having a web hook that lets you plug into a Twitter account.
If you do not have a Twitter account, set one up now. And even if you do have one, create a new development account that is separate from your primary feed. Otherwise, your followers may not appreciate getting your temperature sensor tweets.
- On the ThingSpeak site, select Apps from the menu and then ThingTweet.
- Under the ThingTweet App, select Link Twitter Account. This will redirect you to Twitter so you can authorize ThingSpeak access to your account. If you want to proceed with the rest of this recipe, you will need to give permission for authorization.
Once you have confirmed the right Twitter account, Twitter will send you back to ThingSpeak.
- After the authorization process, the ThingSpeak app generates a ThingTweet API Key that we will need to use in our code, as shown in the following screenshot:
- Copy and paste this new API Key to line 33 of the code in the Cloud9 window, where it says
THINGTWEET_TWITTER_API_KEY_HERE
and the two CHANNEL-IDs to the designated spots in the code:request.post('https://api.thingspeak.com/apps/thingtweet/1/statuses/update', {form:{api_key: 'THINGTWEET_TWITTER_API_KEY_HERE', status: "The current Ground Control temperature is %%channel_CHANNEL-ID_field_1%% F, %%channel_CHANNEL-ID_field_2%% C"}}); }
Note
All the parameters from the Twitter API statuses/update are possible, including geolocation. You can learn more about the ThingSpeak API and its Twitter app on their site at https://thingspeak.com/docs/thingtweet/.
- Last but not least, click on RUN in the IDE. Let's keep our fingers crossed because your BBB's Ground Control Temperature will begin to send temperature updates to your Twitter account.
Three cheers for Ground Control Temperature!
See also
You will soon learn that there is a vast array of new ventures playing in the IoT cloud services sandbox. As most of them are nascent businesses in a newly emerging industry, it is difficult to predict who will emerge as go-to platforms in the future. However, a handful of players are worth mentioning for their ease of use or their strong positioning on the marketplace:
- Cloud deployment: Deploying software updates to multiple remote devices will become an increasing challenge as the IoT continues to grow. Two players, Resin.io (https://www.resin.io/) and Docker (https://www.docker.com/), are leading the charge in creating a platform for containerizing your applications, making it easy to deploy packages to all your devices over the cloud.
- Data display and hosting: Many businesses in the IoT space are trying to make it easier for you to manage and display your IoT data in a slicker package and simultaneously host with them. Here are a couple of them:
- Initial state (https://www.initialstate.com/)
- Ubidots (http://ubidots.com/)
- Messaging and alerts: Dweet.io/Freeboard (http://dweet.io/)
- Connecting to web services through open APIs: Ship.iot (https://shipiot.net)
- Toolsets to hook up IoT devices including the following sample:
- IBM's Nodered.js (http://nodered.org/)
- Adafruit I/O (https://www.adafruit.com/io)
Getting ready
The following materials will be needed:
- BBB powered via 5V supply.
- Ethernet or Wi-Fi connectivity.
- Breadboard.
- 3x jumper wires.
- The TMP36 temperature sensor—this is the same sensor as the one we used in Chapter 3, Physical Computing Recipes Using JavaScript, the BoneScript Library, and Python. As a reminder, this low-cost sensor is readily available from numerous sources, including suppliers such as Sparkfun (https://www.sparkfun.com/products/10988).
How to do it…
Perform the following steps to use sensors and data with ThingSpeak:
- If BBB is not already off, turn it off.
- Using the following fritzing diagram, wire your powered down BBB:
You may remember this configuration from Chapter 3, Physical Computing Recipes Using JavaScript, the BoneScript Library, and Python as the wiring is exactly the same: GND uses the analog ground P9_34 (GNDA_ADC), 3V PWR at P9_3, and the sensor pin at P9_38.
- Power your BBB and log in via SSH.
- Sign up for a new account at ThingSpeak (https://thingspeak.com/), a free cloud service for data publishing and creating IoT-style products.
- Follow the prompts on the ThingSpeak site on how to set up a channel for your account. Just for fun, let's name the channel as
Ground Control Temperature
. - At the bottom of the same Channel Settings screen, create a second field called
Field Label 2
, as shown in the following screenshot: - You can now see the blank slate charts that have been created for the channel that will receive data from the BBB's sensor:
- From your GitHub repo, download the BoneScript (Node.js) code for this recipe to your BBB with the following command:
$ git clone https://github.com/HudsonWerks/tmp36-sensor-thingspeak.git
Note
The repo also includes a Python script example; however, we will only review the node version of the recipe here.
- Navigate to the new directory that we just created and open the Node.js file with the following command:
$ cd tmp36-sensor-thingspeak $ sudo nano tmp36-thingspeak.js
- In a browser on your client desktop, open the Cloud9 IDE and create a new JavaScript file. Then, copy and paste the code from the open
nano
window on your BBB to the Cloud9 file. - Before trying to send data to ThingSpeak, we should first verify that our sensor, wiring, and basic code are functioning properly. Now, in your Cloud9 window, click on the RUN button. If all goes well, the console output in the IDE should show readings similar to the following code:
debugger listening on port 15454 Sensor reading started. Output at 10-sec intervals. Temperature at Ground Control for Tue, 11 Aug 2015 19:20:21 GMT Fahrenheit: 64.4 Celsius: 18 _____________ Temperature at Ground Control for Tue, 11 Aug 2015 19:20:31 GMT Fahrenheit: 63.86 Celsius: 17.7
If you are not getting readings from the sensor, go back and check your wiring.
- Next, we will hook up our code to the ThingSpeak channel that we set up in the first part of this recipe using the generated API. Back on the ThingSpeak Channels tab, drill down to the new channel you created and search for the API Keys tab option. Select this tab and then copy (Ctrl + C) the Write API Key generated, as shown in the following screenshot:
- Back in the Cloud9 window, on line 30 of the
tmp36
code window, paste your ThingSpeak Write API key to the designated part of the code as follows://Post temperature data to ThingSpeak request.post('http://api.thingspeak.com:80/update',{form:{api_key: 'THINGSPEAK_WRITE_API_KEY_HERE', field1: temp_f, field2: temp_c}});
- Now, it's time to see your temperature readings that is displayed on the ThingSpeak cloud service. So, as you again click on RUN in the IDE, your Cloud9 console should be outputting temperature readings as before. Within a few moments, back on the ThingSpeak channel, data points should be appearing at 10-second intervals on the screen, plotting the fluctuations of Ground Control Temperature of your room, as shown in the following screenshot:
- Last but not least, we want to make the sensor data visible through yet another method, this time using Twitter. As Twitter is free and readily available on your smartphone, it serves as a useful channel to funnel IoT data. ThingSpeak simplifies the process considerably by having a web hook that lets you plug into a Twitter account.
If you do not have a Twitter account, set one up now. And even if you do have one, create a new development account that is separate from your primary feed. Otherwise, your followers may not appreciate getting your temperature sensor tweets.
- On the ThingSpeak site, select Apps from the menu and then ThingTweet.
- Under the ThingTweet App, select Link Twitter Account. This will redirect you to Twitter so you can authorize ThingSpeak access to your account. If you want to proceed with the rest of this recipe, you will need to give permission for authorization.
Once you have confirmed the right Twitter account, Twitter will send you back to ThingSpeak.
- After the authorization process, the ThingSpeak app generates a ThingTweet API Key that we will need to use in our code, as shown in the following screenshot:
- Copy and paste this new API Key to line 33 of the code in the Cloud9 window, where it says
THINGTWEET_TWITTER_API_KEY_HERE
and the two CHANNEL-IDs to the designated spots in the code:request.post('https://api.thingspeak.com/apps/thingtweet/1/statuses/update', {form:{api_key: 'THINGTWEET_TWITTER_API_KEY_HERE', status: "The current Ground Control temperature is %%channel_CHANNEL-ID_field_1%% F, %%channel_CHANNEL-ID_field_2%% C"}}); }
Note
All the parameters from the Twitter API statuses/update are possible, including geolocation. You can learn more about the ThingSpeak API and its Twitter app on their site at https://thingspeak.com/docs/thingtweet/.
- Last but not least, click on RUN in the IDE. Let's keep our fingers crossed because your BBB's Ground Control Temperature will begin to send temperature updates to your Twitter account.
Three cheers for Ground Control Temperature!
See also
You will soon learn that there is a vast array of new ventures playing in the IoT cloud services sandbox. As most of them are nascent businesses in a newly emerging industry, it is difficult to predict who will emerge as go-to platforms in the future. However, a handful of players are worth mentioning for their ease of use or their strong positioning on the marketplace:
- Cloud deployment: Deploying software updates to multiple remote devices will become an increasing challenge as the IoT continues to grow. Two players, Resin.io (https://www.resin.io/) and Docker (https://www.docker.com/), are leading the charge in creating a platform for containerizing your applications, making it easy to deploy packages to all your devices over the cloud.
- Data display and hosting: Many businesses in the IoT space are trying to make it easier for you to manage and display your IoT data in a slicker package and simultaneously host with them. Here are a couple of them:
- Initial state (https://www.initialstate.com/)
- Ubidots (http://ubidots.com/)
- Messaging and alerts: Dweet.io/Freeboard (http://dweet.io/)
- Connecting to web services through open APIs: Ship.iot (https://shipiot.net)
- Toolsets to hook up IoT devices including the following sample:
- IBM's Nodered.js (http://nodered.org/)
- Adafruit I/O (https://www.adafruit.com/io)
How to do it…
Perform the following steps to use sensors and data with ThingSpeak:
- If BBB is not already off, turn it off.
- Using the following fritzing diagram, wire your powered down BBB:
You may remember this configuration from Chapter 3, Physical Computing Recipes Using JavaScript, the BoneScript Library, and Python as the wiring is exactly the same: GND uses the analog ground P9_34 (GNDA_ADC), 3V PWR at P9_3, and the sensor pin at P9_38.
- Power your BBB and log in via SSH.
- Sign up for a new account at ThingSpeak (https://thingspeak.com/), a free cloud service for data publishing and creating IoT-style products.
- Follow the prompts on the ThingSpeak site on how to set up a channel for your account. Just for fun, let's name the channel as
Ground Control Temperature
. - At the bottom of the same Channel Settings screen, create a second field called
Field Label 2
, as shown in the following screenshot: - You can now see the blank slate charts that have been created for the channel that will receive data from the BBB's sensor:
- From your GitHub repo, download the BoneScript (Node.js) code for this recipe to your BBB with the following command:
$ git clone https://github.com/HudsonWerks/tmp36-sensor-thingspeak.git
Note
The repo also includes a Python script example; however, we will only review the node version of the recipe here.
- Navigate to the new directory that we just created and open the Node.js file with the following command:
$ cd tmp36-sensor-thingspeak $ sudo nano tmp36-thingspeak.js
- In a browser on your client desktop, open the Cloud9 IDE and create a new JavaScript file. Then, copy and paste the code from the open
nano
window on your BBB to the Cloud9 file. - Before trying to send data to ThingSpeak, we should first verify that our sensor, wiring, and basic code are functioning properly. Now, in your Cloud9 window, click on the RUN button. If all goes well, the console output in the IDE should show readings similar to the following code:
debugger listening on port 15454 Sensor reading started. Output at 10-sec intervals. Temperature at Ground Control for Tue, 11 Aug 2015 19:20:21 GMT Fahrenheit: 64.4 Celsius: 18 _____________ Temperature at Ground Control for Tue, 11 Aug 2015 19:20:31 GMT Fahrenheit: 63.86 Celsius: 17.7
If you are not getting readings from the sensor, go back and check your wiring.
- Next, we will hook up our code to the ThingSpeak channel that we set up in the first part of this recipe using the generated API. Back on the ThingSpeak Channels tab, drill down to the new channel you created and search for the API Keys tab option. Select this tab and then copy (Ctrl + C) the Write API Key generated, as shown in the following screenshot:
- Back in the Cloud9 window, on line 30 of the
tmp36
code window, paste your ThingSpeak Write API key to the designated part of the code as follows://Post temperature data to ThingSpeak request.post('http://api.thingspeak.com:80/update',{form:{api_key: 'THINGSPEAK_WRITE_API_KEY_HERE', field1: temp_f, field2: temp_c}});
- Now, it's time to see your temperature readings that is displayed on the ThingSpeak cloud service. So, as you again click on RUN in the IDE, your Cloud9 console should be outputting temperature readings as before. Within a few moments, back on the ThingSpeak channel, data points should be appearing at 10-second intervals on the screen, plotting the fluctuations of Ground Control Temperature of your room, as shown in the following screenshot:
- Last but not least, we want to make the sensor data visible through yet another method, this time using Twitter. As Twitter is free and readily available on your smartphone, it serves as a useful channel to funnel IoT data. ThingSpeak simplifies the process considerably by having a web hook that lets you plug into a Twitter account.
If you do not have a Twitter account, set one up now. And even if you do have one, create a new development account that is separate from your primary feed. Otherwise, your followers may not appreciate getting your temperature sensor tweets.
- On the ThingSpeak site, select Apps from the menu and then ThingTweet.
- Under the ThingTweet App, select Link Twitter Account. This will redirect you to Twitter so you can authorize ThingSpeak access to your account. If you want to proceed with the rest of this recipe, you will need to give permission for authorization.
Once you have confirmed the right Twitter account, Twitter will send you back to ThingSpeak.
- After the authorization process, the ThingSpeak app generates a ThingTweet API Key that we will need to use in our code, as shown in the following screenshot:
- Copy and paste this new API Key to line 33 of the code in the Cloud9 window, where it says
THINGTWEET_TWITTER_API_KEY_HERE
and the two CHANNEL-IDs to the designated spots in the code:request.post('https://api.thingspeak.com/apps/thingtweet/1/statuses/update', {form:{api_key: 'THINGTWEET_TWITTER_API_KEY_HERE', status: "The current Ground Control temperature is %%channel_CHANNEL-ID_field_1%% F, %%channel_CHANNEL-ID_field_2%% C"}}); }
Note
All the parameters from the Twitter API statuses/update are possible, including geolocation. You can learn more about the ThingSpeak API and its Twitter app on their site at https://thingspeak.com/docs/thingtweet/.
- Last but not least, click on RUN in the IDE. Let's keep our fingers crossed because your BBB's Ground Control Temperature will begin to send temperature updates to your Twitter account.
Three cheers for Ground Control Temperature!
See also
You will soon learn that there is a vast array of new ventures playing in the IoT cloud services sandbox. As most of them are nascent businesses in a newly emerging industry, it is difficult to predict who will emerge as go-to platforms in the future. However, a handful of players are worth mentioning for their ease of use or their strong positioning on the marketplace:
- Cloud deployment: Deploying software updates to multiple remote devices will become an increasing challenge as the IoT continues to grow. Two players, Resin.io (https://www.resin.io/) and Docker (https://www.docker.com/), are leading the charge in creating a platform for containerizing your applications, making it easy to deploy packages to all your devices over the cloud.
- Data display and hosting: Many businesses in the IoT space are trying to make it easier for you to manage and display your IoT data in a slicker package and simultaneously host with them. Here are a couple of them:
- Initial state (https://www.initialstate.com/)
- Ubidots (http://ubidots.com/)
- Messaging and alerts: Dweet.io/Freeboard (http://dweet.io/)
- Connecting to web services through open APIs: Ship.iot (https://shipiot.net)
- Toolsets to hook up IoT devices including the following sample:
- IBM's Nodered.js (http://nodered.org/)
- Adafruit I/O (https://www.adafruit.com/io)
See also
You will soon learn that there is a vast array of new ventures playing in the IoT cloud services sandbox. As most of them are nascent businesses in a newly emerging industry, it is difficult to predict who will emerge as go-to platforms in the future. However, a handful of players are worth mentioning for their ease of use or their strong positioning on the marketplace:
- Cloud deployment: Deploying software updates to multiple remote devices will become an increasing challenge as the IoT continues to grow. Two players, Resin.io (https://www.resin.io/) and Docker (https://www.docker.com/), are leading the charge in creating a platform for containerizing your applications, making it easy to deploy packages to all your devices over the cloud.
- Data display and hosting: Many businesses in the IoT space are trying to make it easier for you to manage and display your IoT data in a slicker package and simultaneously host with them. Here are a couple of them:
- Initial state (https://www.initialstate.com/)
- Ubidots (http://ubidots.com/)
- Messaging and alerts: Dweet.io/Freeboard (http://dweet.io/)
- Connecting to web services through open APIs: Ship.iot (https://shipiot.net)
- Toolsets to hook up IoT devices including the following sample:
- IBM's Nodered.js (http://nodered.org/)
- Adafruit I/O (https://www.adafruit.com/io)
Making things smarter – building a wireless digital picture frame
Taking mundane objects and connecting them to one another is one of the key intentions of the whole IoT phenomenon. In our next recipe, we will create a digital picture frame. However, ours is is not the typical off-the-shelf version where you load images from an SD card. Instead, we will use a combination of web services that are commonly used in IoT together with a wireless image player to update the digital picture frame dynamically and seamlessly from a smartphone.
Getting ready
The materials needed are as follows:
- A smartphone with internet connectivity
- The BBB powered by 5V
- A Wi-Fi dongle
- An LCD (5 inches or larger)
You will also need to set up two web service accounts:
- Dropbox: The free plan is adequate (http://www.dropbox.com)
- IFTTT: This is a free service (http://www.ifttt.com)
Using IFTTT
For this recipe, we will incorporate the If This Then That (IFTTT) web service. Although not perfect, IFTTT is a fun, rapid development tool for prototyping IoT scenarios and use cases. There are other ways to perform what I will outline later; you could hook up other popular third-party apps, such as Instagram, Flickr, and Twitter. However, I prefer to keep the additional installations at a minimum and establish more of a least common denominator environment that provides a simpler development path.
For long-term serious product builds, IFTTT is not a good choice because it is too "black box", too opaque in its functionality to rely on for final designs. However, for rapid protoyping and idea generating, it is highly useful. With IFTTT, you can iterate quickly and nimbly using a host of different web services that will always lead to new ideas and directions for your development.
How to do it...
Part one: The smartphone setup
Perform the following steps:
- On your smartphone, shoot a photograph with a camera app.
- Save the photo to a custom album on your phone that you need to create. Name it
NowPix
. - Set up the IFTTT trigger on your phone to send the saved album file to Dropbox.
Setting up and testing the Dropbox script on the BBB
Perform the following steps:
- If you do not already have a Dropbox account, sign up for a free account at https://www.dropbox.com/home.
- Download and install a custom bash script called Dropbox Uploader. This is a wonderfully useful open source tool created by developer Andrea Fabrizi. The script provides an easy method to interact directly with the Dropbox's API authentication process, so providing your username and password is not necessary.
- Now, make sure that you are in your home directory:
$ cd
- Then, clone the Dropbox Uploader code using the following command:
$ git clone https://github.com/andreafabrizi/Dropbox-Uploader/
- Make sure that the directory was created, as shown in the following command:
$ cd Dropbox-Uploader
- Set permissions with the following command:
$chmod +x dropbox_uploader.sh $./dropbox_uploader.sh
- Then, run the script as follows:
~/Dropbox-Uploader$ ./dropbox_uploader.sh
You should see the screen output with a set of instructions:
This is the first time you run this script.
Back to your desktop client
Before responding to the terminal prompts, you will now need to set up a Dropbox App via your desktop client (PC or Mac). This app will hook to the Dropbox Uploader script.
Perform the following steps:
- Open the following URL on the desktop in your browser and log in using your Dropbox account at https://www2.dropbox.com/developers/apps.
- Click on Create App and then select the Dropbox API app.
- Select Files and Datastores. The rest of the fields should be filled out in the following manner:
Can your app be limited to its own folder?
No
What type of files does your app need access to?
Specific file types—My app only needs access to certain file types, like text or photos.
Last question, what type of files will your app use?
Images
- Give the app a name in the last text field. Mine is called
NowPix
to remain consistent with the directory/album name that we set up on the iPhone. Then, finish by clicking on the Create App button. - Now, generate an App key.
Back to the BBB
The next series of steps continue with the verification/authentication process using Dropbox. Perform the following steps:
- In the open terminal window and at the appropriate prompt, paste the App Key generated in the previous step and follow the onscreen prompts.
- When your new app is successfully created, enter the App Key, App Secret, and the permission type shown in the confirmation page as follows:
# App Key: YOUR_API_KEY_HERE
- Hit the return (Enter) key after you input the appropriate data, given the next several terminal prompts.
Now, App Secret has been generated. Cut and paste that string from the Dropbox to the terminal window, as shown in the following code:
# App secret abcdefghijklmnop1234 Permission type, App folder or Full Dropbox [a/f]: App folder (f) App key is abcdefghijklmnop1234, App secret isabcdefghijklmnop1234 and Access level is Full Dropbox. Looks ok? [y/n]: [y/n]: y
Hit return and you are finished at least with the installation.
Note
If you accidentally input the wrong App Key and App Secret (which I did since I have several Dropbox apps), you can reset the access by running the following script:
$ ./dropbox_uploader.sh unlink
Testing and running the script
We now need to verify that the script operates as expected: downloading images from Dropbox and placing them in a specified directory.
- First, we will verify that the content of our IFTTT directory on the Dropbox can be accessed and read properly, so we will list the images that are there:
$ cd Dropbox-Uploader $ ./dropbox_uploader.sh list /IFTTT/iOS_Photos/NowPix
- Go get the actual images and download them to your directory using the following command:
$ ./dropbox_uploader.sh download -s /Apps/NowPix /home/debian/NowPix
We added the
-s
option that skips the already existing files when you download/upload; otherwise, the default parameter is to overwrite the files in the target directory. - Verify that you did, in fact, get the images with the following command:
$ cd NowPix $ ls
- Assuming that your script executed properly and the images were downloaded to the right directory, we now need to set up a process in order for the script to run transparently so that you don't have to run it each time you want to download images. To perform this, we will set up a
cron
job that automatically runs the script at specified intervals. We will begin this part by openingcrontab
in our default editor with the following command:$ crontab -e
The
-e
option tells the shell to open our default editor, which in our case isnano
.Note
You should take note of these comments from the original script developer:
## Running as
cron
jobDropbox Uploader relies on a different configuration file for each system user. The default configuration file location is
HOME_DIRECTORY/.dropbox_uploader
. This means that if you do the setup with your user and then try to run acron
job as root, it will not work.So, when you run this script using
cron
, keep the following things in mind:Remember to set up the script that the user used to run the
cron
job.Always use the
-f
option to specify the full configuration file path because sometimes in thecron
environment, the home folder path is not detected correctly.For security reasons, I recommend you to not share the same configuration file with different users.
- Add the following code to the end of the file that opens on your screen:
*/3 * * * * /home/debian/Dropbox-Uploader/dropbox_uploader.sh -s download /IFTTT/iOS_Photos/NowPix /home/debian/
The number
3
is the frequency in which thecron
job will run, which in our case is every 3 minutes. We have it set for such a high frequency only for testing purposes. When we are finished with our testing, you should change this number to a higher one, perhaps every few hours or longer, depending on how often you plan to add photos to yourNowPix
digital picture frame.The rest of the line with all the asterisks corresponds to the following layout for a
cron
job:minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command
- With
cron
, it is a good idea to verify that the job has run as expected. You can perform this easily with the following command that checks an e-mail file thatcrontab
automatically runs once acron
job has been set up:$ tail -f /var/mail/debian
You should see a log of the system e-mails that
crontab
will send, including the output from thedownloader.sh
script. This output should mirror the kind of output you saw when you were running the earlier bash script in the terminal window. - Next, we need to install and set up a package that will open and cycle the images that we will download on the BBB. For this, we will use
feh
, a lightweight and powerful image viewer, as shown in the following code:$ sudo apt-get update $ sudo apt-get install feh
feh
requires-x
so that you can run the app remotely via vnc as follows:$ feh -x
- Now, we can view all our photos taken on our smartphone as a slide show:
$ feh -FD10 /home/debian/NowPix
FD is the command to run a slideshow, whereas the number after FD is an adjustable play duration for the image.
The program must also point to the directory with the images that will run as a slideshow. Use the Esc button on your desktop to exit from the slideshow.
You may see another permissions-related error when you try to execute the
feh
program. The error may say something similar to the following code:Invalid MIT-MAGIC-COOKIE-1
If so, run the following command to delete the
.Xauthority
file:$ rm .Xauthority*
- Next, we will create a systemd service (remember that?!) that runs the command to load the images and display them in a loop on bootup. So, log in as root, as shown in the following code:
$ sudo -i
- Navigate to the systemd directory with the following code:
# cd /lib/systemd/system
- Now, create a new service file as follows:
# sudo nano nowpix.service
- Then, paste the following code to the editor window:
[Unit] Description=Run NowPix images using Feh on boot [Service] Type=simple ExecStart=/usr/bin/feh -FD10 /home/debian/NowPix Environment=DISPLAY=:0 SyslogIdentifier=fehslideshow Restart=on-failure RestartSec=5 [Install] WantedBy=multi-user.target
- Start the systemd service with the following code:
# systemctl start nowpix.service
- Finally, run the following command that enables the service to start at bootup:
# systemctl enable nowpix.service
- Now, reboot your BBB. If all is well, you should now have pictures cycling on your screen updated from your new photos on your smartphone.
See also
Crontabs is a bigger subject to learn and useful in many scenarios, where you want to time events on your BBB. For more information, refer to:
Getting ready
The materials needed are as follows:
- A smartphone with internet connectivity
- The BBB powered by 5V
- A Wi-Fi dongle
- An LCD (5 inches or larger)
You will also need to set up two web service accounts:
- Dropbox: The free plan is adequate (http://www.dropbox.com)
- IFTTT: This is a free service (http://www.ifttt.com)
Using IFTTT
For this recipe, we will incorporate the If This Then That (IFTTT) web service. Although not perfect, IFTTT is a fun, rapid development tool for prototyping IoT scenarios and use cases. There are other ways to perform what I will outline later; you could hook up other popular third-party apps, such as Instagram, Flickr, and Twitter. However, I prefer to keep the additional installations at a minimum and establish more of a least common denominator environment that provides a simpler development path.
For long-term serious product builds, IFTTT is not a good choice because it is too "black box", too opaque in its functionality to rely on for final designs. However, for rapid protoyping and idea generating, it is highly useful. With IFTTT, you can iterate quickly and nimbly using a host of different web services that will always lead to new ideas and directions for your development.
How to do it...
Part one: The smartphone setup
Perform the following steps:
- On your smartphone, shoot a photograph with a camera app.
- Save the photo to a custom album on your phone that you need to create. Name it
NowPix
. - Set up the IFTTT trigger on your phone to send the saved album file to Dropbox.
Setting up and testing the Dropbox script on the BBB
Perform the following steps:
- If you do not already have a Dropbox account, sign up for a free account at https://www.dropbox.com/home.
- Download and install a custom bash script called Dropbox Uploader. This is a wonderfully useful open source tool created by developer Andrea Fabrizi. The script provides an easy method to interact directly with the Dropbox's API authentication process, so providing your username and password is not necessary.
- Now, make sure that you are in your home directory:
$ cd
- Then, clone the Dropbox Uploader code using the following command:
$ git clone https://github.com/andreafabrizi/Dropbox-Uploader/
- Make sure that the directory was created, as shown in the following command:
$ cd Dropbox-Uploader
- Set permissions with the following command:
$chmod +x dropbox_uploader.sh $./dropbox_uploader.sh
- Then, run the script as follows:
~/Dropbox-Uploader$ ./dropbox_uploader.sh
You should see the screen output with a set of instructions:
This is the first time you run this script.
Back to your desktop client
Before responding to the terminal prompts, you will now need to set up a Dropbox App via your desktop client (PC or Mac). This app will hook to the Dropbox Uploader script.
Perform the following steps:
- Open the following URL on the desktop in your browser and log in using your Dropbox account at https://www2.dropbox.com/developers/apps.
- Click on Create App and then select the Dropbox API app.
- Select Files and Datastores. The rest of the fields should be filled out in the following manner:
Can your app be limited to its own folder?
No
What type of files does your app need access to?
Specific file types—My app only needs access to certain file types, like text or photos.
Last question, what type of files will your app use?
Images
- Give the app a name in the last text field. Mine is called
NowPix
to remain consistent with the directory/album name that we set up on the iPhone. Then, finish by clicking on the Create App button. - Now, generate an App key.
Back to the BBB
The next series of steps continue with the verification/authentication process using Dropbox. Perform the following steps:
- In the open terminal window and at the appropriate prompt, paste the App Key generated in the previous step and follow the onscreen prompts.
- When your new app is successfully created, enter the App Key, App Secret, and the permission type shown in the confirmation page as follows:
# App Key: YOUR_API_KEY_HERE
- Hit the return (Enter) key after you input the appropriate data, given the next several terminal prompts.
Now, App Secret has been generated. Cut and paste that string from the Dropbox to the terminal window, as shown in the following code:
# App secret abcdefghijklmnop1234 Permission type, App folder or Full Dropbox [a/f]: App folder (f) App key is abcdefghijklmnop1234, App secret isabcdefghijklmnop1234 and Access level is Full Dropbox. Looks ok? [y/n]: [y/n]: y
Hit return and you are finished at least with the installation.
Note
If you accidentally input the wrong App Key and App Secret (which I did since I have several Dropbox apps), you can reset the access by running the following script:
$ ./dropbox_uploader.sh unlink
Testing and running the script
We now need to verify that the script operates as expected: downloading images from Dropbox and placing them in a specified directory.
- First, we will verify that the content of our IFTTT directory on the Dropbox can be accessed and read properly, so we will list the images that are there:
$ cd Dropbox-Uploader $ ./dropbox_uploader.sh list /IFTTT/iOS_Photos/NowPix
- Go get the actual images and download them to your directory using the following command:
$ ./dropbox_uploader.sh download -s /Apps/NowPix /home/debian/NowPix
We added the
-s
option that skips the already existing files when you download/upload; otherwise, the default parameter is to overwrite the files in the target directory. - Verify that you did, in fact, get the images with the following command:
$ cd NowPix $ ls
- Assuming that your script executed properly and the images were downloaded to the right directory, we now need to set up a process in order for the script to run transparently so that you don't have to run it each time you want to download images. To perform this, we will set up a
cron
job that automatically runs the script at specified intervals. We will begin this part by openingcrontab
in our default editor with the following command:$ crontab -e
The
-e
option tells the shell to open our default editor, which in our case isnano
.Note
You should take note of these comments from the original script developer:
## Running as
cron
jobDropbox Uploader relies on a different configuration file for each system user. The default configuration file location is
HOME_DIRECTORY/.dropbox_uploader
. This means that if you do the setup with your user and then try to run acron
job as root, it will not work.So, when you run this script using
cron
, keep the following things in mind:Remember to set up the script that the user used to run the
cron
job.Always use the
-f
option to specify the full configuration file path because sometimes in thecron
environment, the home folder path is not detected correctly.For security reasons, I recommend you to not share the same configuration file with different users.
- Add the following code to the end of the file that opens on your screen:
*/3 * * * * /home/debian/Dropbox-Uploader/dropbox_uploader.sh -s download /IFTTT/iOS_Photos/NowPix /home/debian/
The number
3
is the frequency in which thecron
job will run, which in our case is every 3 minutes. We have it set for such a high frequency only for testing purposes. When we are finished with our testing, you should change this number to a higher one, perhaps every few hours or longer, depending on how often you plan to add photos to yourNowPix
digital picture frame.The rest of the line with all the asterisks corresponds to the following layout for a
cron
job:minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command
- With
cron
, it is a good idea to verify that the job has run as expected. You can perform this easily with the following command that checks an e-mail file thatcrontab
automatically runs once acron
job has been set up:$ tail -f /var/mail/debian
You should see a log of the system e-mails that
crontab
will send, including the output from thedownloader.sh
script. This output should mirror the kind of output you saw when you were running the earlier bash script in the terminal window. - Next, we need to install and set up a package that will open and cycle the images that we will download on the BBB. For this, we will use
feh
, a lightweight and powerful image viewer, as shown in the following code:$ sudo apt-get update $ sudo apt-get install feh
feh
requires-x
so that you can run the app remotely via vnc as follows:$ feh -x
- Now, we can view all our photos taken on our smartphone as a slide show:
$ feh -FD10 /home/debian/NowPix
FD is the command to run a slideshow, whereas the number after FD is an adjustable play duration for the image.
The program must also point to the directory with the images that will run as a slideshow. Use the Esc button on your desktop to exit from the slideshow.
You may see another permissions-related error when you try to execute the
feh
program. The error may say something similar to the following code:Invalid MIT-MAGIC-COOKIE-1
If so, run the following command to delete the
.Xauthority
file:$ rm .Xauthority*
- Next, we will create a systemd service (remember that?!) that runs the command to load the images and display them in a loop on bootup. So, log in as root, as shown in the following code:
$ sudo -i
- Navigate to the systemd directory with the following code:
# cd /lib/systemd/system
- Now, create a new service file as follows:
# sudo nano nowpix.service
- Then, paste the following code to the editor window:
[Unit] Description=Run NowPix images using Feh on boot [Service] Type=simple ExecStart=/usr/bin/feh -FD10 /home/debian/NowPix Environment=DISPLAY=:0 SyslogIdentifier=fehslideshow Restart=on-failure RestartSec=5 [Install] WantedBy=multi-user.target
- Start the systemd service with the following code:
# systemctl start nowpix.service
- Finally, run the following command that enables the service to start at bootup:
# systemctl enable nowpix.service
- Now, reboot your BBB. If all is well, you should now have pictures cycling on your screen updated from your new photos on your smartphone.
See also
Crontabs is a bigger subject to learn and useful in many scenarios, where you want to time events on your BBB. For more information, refer to:
How to do it...
Part one: The smartphone setup
Perform the following steps:
- On your smartphone, shoot a photograph with a camera app.
- Save the photo to a custom album on your phone that you need to create. Name it
NowPix
. - Set up the IFTTT trigger on your phone to send the saved album file to Dropbox.
Setting up and testing the Dropbox script on the BBB
Perform the following steps:
- If you do not already have a Dropbox account, sign up for a free account at https://www.dropbox.com/home.
- Download and install a custom bash script called Dropbox Uploader. This is a wonderfully useful open source tool created by developer Andrea Fabrizi. The script provides an easy method to interact directly with the Dropbox's API authentication process, so providing your username and password is not necessary.
- Now, make sure that you are in your home directory:
$ cd
- Then, clone the Dropbox Uploader code using the following command:
$ git clone https://github.com/andreafabrizi/Dropbox-Uploader/
- Make sure that the directory was created, as shown in the following command:
$ cd Dropbox-Uploader
- Set permissions with the following command:
$chmod +x dropbox_uploader.sh $./dropbox_uploader.sh
- Then, run the script as follows:
~/Dropbox-Uploader$ ./dropbox_uploader.sh
You should see the screen output with a set of instructions:
This is the first time you run this script.
Back to your desktop client
Before responding to the terminal prompts, you will now need to set up a Dropbox App via your desktop client (PC or Mac). This app will hook to the Dropbox Uploader script.
Perform the following steps:
- Open the following URL on the desktop in your browser and log in using your Dropbox account at https://www2.dropbox.com/developers/apps.
- Click on Create App and then select the Dropbox API app.
- Select Files and Datastores. The rest of the fields should be filled out in the following manner:
Can your app be limited to its own folder?
No
What type of files does your app need access to?
Specific file types—My app only needs access to certain file types, like text or photos.
Last question, what type of files will your app use?
Images
- Give the app a name in the last text field. Mine is called
NowPix
to remain consistent with the directory/album name that we set up on the iPhone. Then, finish by clicking on the Create App button. - Now, generate an App key.
Back to the BBB
The next series of steps continue with the verification/authentication process using Dropbox. Perform the following steps:
- In the open terminal window and at the appropriate prompt, paste the App Key generated in the previous step and follow the onscreen prompts.
- When your new app is successfully created, enter the App Key, App Secret, and the permission type shown in the confirmation page as follows:
# App Key: YOUR_API_KEY_HERE
- Hit the return (Enter) key after you input the appropriate data, given the next several terminal prompts.
Now, App Secret has been generated. Cut and paste that string from the Dropbox to the terminal window, as shown in the following code:
# App secret abcdefghijklmnop1234 Permission type, App folder or Full Dropbox [a/f]: App folder (f) App key is abcdefghijklmnop1234, App secret isabcdefghijklmnop1234 and Access level is Full Dropbox. Looks ok? [y/n]: [y/n]: y
Hit return and you are finished at least with the installation.
Note
If you accidentally input the wrong App Key and App Secret (which I did since I have several Dropbox apps), you can reset the access by running the following script:
$ ./dropbox_uploader.sh unlink
Testing and running the script
We now need to verify that the script operates as expected: downloading images from Dropbox and placing them in a specified directory.
- First, we will verify that the content of our IFTTT directory on the Dropbox can be accessed and read properly, so we will list the images that are there:
$ cd Dropbox-Uploader $ ./dropbox_uploader.sh list /IFTTT/iOS_Photos/NowPix
- Go get the actual images and download them to your directory using the following command:
$ ./dropbox_uploader.sh download -s /Apps/NowPix /home/debian/NowPix
We added the
-s
option that skips the already existing files when you download/upload; otherwise, the default parameter is to overwrite the files in the target directory. - Verify that you did, in fact, get the images with the following command:
$ cd NowPix $ ls
- Assuming that your script executed properly and the images were downloaded to the right directory, we now need to set up a process in order for the script to run transparently so that you don't have to run it each time you want to download images. To perform this, we will set up a
cron
job that automatically runs the script at specified intervals. We will begin this part by openingcrontab
in our default editor with the following command:$ crontab -e
The
-e
option tells the shell to open our default editor, which in our case isnano
.Note
You should take note of these comments from the original script developer:
## Running as
cron
jobDropbox Uploader relies on a different configuration file for each system user. The default configuration file location is
HOME_DIRECTORY/.dropbox_uploader
. This means that if you do the setup with your user and then try to run acron
job as root, it will not work.So, when you run this script using
cron
, keep the following things in mind:Remember to set up the script that the user used to run the
cron
job.Always use the
-f
option to specify the full configuration file path because sometimes in thecron
environment, the home folder path is not detected correctly.For security reasons, I recommend you to not share the same configuration file with different users.
- Add the following code to the end of the file that opens on your screen:
*/3 * * * * /home/debian/Dropbox-Uploader/dropbox_uploader.sh -s download /IFTTT/iOS_Photos/NowPix /home/debian/
The number
3
is the frequency in which thecron
job will run, which in our case is every 3 minutes. We have it set for such a high frequency only for testing purposes. When we are finished with our testing, you should change this number to a higher one, perhaps every few hours or longer, depending on how often you plan to add photos to yourNowPix
digital picture frame.The rest of the line with all the asterisks corresponds to the following layout for a
cron
job:minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command
- With
cron
, it is a good idea to verify that the job has run as expected. You can perform this easily with the following command that checks an e-mail file thatcrontab
automatically runs once acron
job has been set up:$ tail -f /var/mail/debian
You should see a log of the system e-mails that
crontab
will send, including the output from thedownloader.sh
script. This output should mirror the kind of output you saw when you were running the earlier bash script in the terminal window. - Next, we need to install and set up a package that will open and cycle the images that we will download on the BBB. For this, we will use
feh
, a lightweight and powerful image viewer, as shown in the following code:$ sudo apt-get update $ sudo apt-get install feh
feh
requires-x
so that you can run the app remotely via vnc as follows:$ feh -x
- Now, we can view all our photos taken on our smartphone as a slide show:
$ feh -FD10 /home/debian/NowPix
FD is the command to run a slideshow, whereas the number after FD is an adjustable play duration for the image.
The program must also point to the directory with the images that will run as a slideshow. Use the Esc button on your desktop to exit from the slideshow.
You may see another permissions-related error when you try to execute the
feh
program. The error may say something similar to the following code:Invalid MIT-MAGIC-COOKIE-1
If so, run the following command to delete the
.Xauthority
file:$ rm .Xauthority*
- Next, we will create a systemd service (remember that?!) that runs the command to load the images and display them in a loop on bootup. So, log in as root, as shown in the following code:
$ sudo -i
- Navigate to the systemd directory with the following code:
# cd /lib/systemd/system
- Now, create a new service file as follows:
# sudo nano nowpix.service
- Then, paste the following code to the editor window:
[Unit] Description=Run NowPix images using Feh on boot [Service] Type=simple ExecStart=/usr/bin/feh -FD10 /home/debian/NowPix Environment=DISPLAY=:0 SyslogIdentifier=fehslideshow Restart=on-failure RestartSec=5 [Install] WantedBy=multi-user.target
- Start the systemd service with the following code:
# systemctl start nowpix.service
- Finally, run the following command that enables the service to start at bootup:
# systemctl enable nowpix.service
- Now, reboot your BBB. If all is well, you should now have pictures cycling on your screen updated from your new photos on your smartphone.
See also
Crontabs is a bigger subject to learn and useful in many scenarios, where you want to time events on your BBB. For more information, refer to:
See also
Crontabs is a bigger subject to learn and useful in many scenarios, where you want to time events on your BBB. For more information, refer to: