9
PI SPY PART 2: WI-FI AND BLUETOOTH TRACKING

YOU CAN USE YOUR NEW RASPBERRY PI SKILLS TO SPY ON WHOEVER IS IN YOUR HOUSE BY LOCATING SIGNALS FROM THEIR TECHNOLOGY. ALMOST EVERYONE HAS A SMARTPHONE, TABLET, OR ANOTHER DEVICE THAT TRANSMITS A LOT OF UNSEEN DATA IN THEIR VICINITY. YOU’LL USE THIS DATA TO DETECT WHO IS AROUND.

You’ll use your Raspberry Pi to detect devices through both your internet router and Bluetooth. You’ll send data from your Raspberry Pi to each device via the internet router or Bluetooth and retrieve information including the device’s name, the device’s type, whether it’s connected, and then whether the person who owns the device is around. This assumes that each device is owned by one person and not, say, shared among the family. Otherwise, knowing who’s around is much harder!

You’ll then create an LED visual display board indicator, or status board, that lights up when a user is in the home and goes off when the user is absent (Figure 9-1).

Image

FIGURE 9-1 A finished status board

WHAT YOU’LL NEED

  • Raspberry Pi Zero W or Raspberry Pi 4 (suggested)
  • 10 female-to-female jumper wires
  • 5 LEDs—or the same number of LEDs as devices you want to track
  • 5 resistors (220 to 330 ohms)
  • Cardboard
  • Pictures (optional)
  • Masking tape (optional)
  • Push button

You can use pictures of your family members or, to disguise the purpose of the status board, random pictures to represent each family member, as I have in Figure 9-1.

CREATING YOUR STATUS BOARD

Let’s begin by creating the status board that will indicate who is in the vicinity.

If you have one, the Raspberry Pi Zero W is the best size for mounting onto the back of your status board, because it’s the smallest Pi. If you’re using a bigger Pi, such as the model 4, you might have to put it next to the status board on a sturdy surface. However, if you do use the Zero W, you may find it easier to make the project by using a model 4 and then transfering the SD card to your Pi Zero W.

Wiring Up the LEDs

Take one of the five LEDs and locate the longer (positive) leg. Wrap one leg from a resistor around this LED leg so that it’s tight and secure, as shown in Figure 9-2. Now attach one end of a female-to-female jumper wire to the shorter (negative) leg of the LED. Attach the other female-to-female jumper wire to the resistor wire. Repeat this step for all five LEDs.

Image

FIGURE 9-2 Wiring up an LED

Adding the LEDs to the Board

On the cardboard you’re using for your status board, lightly mark each location where you want to place an LED. If you’re attaching the Raspberry Pi to the board, ensure that you leave enough space for the Pi and all the wires. Carefully pierce a small hole in the board at each previously marked location to hold each LED in place. You can use a pen or screwdriver to do this. Push each LED through a hole. Stick them down with masking tape to keep things neat and tidy, as well as to reduce the possibility of the wires touching each other and causing a short-out. The back of your status board should look similar to Figure 9-3. Each of the numbers refers to the GPIO pin that the LED is connected to. (See the table on the next page for the GPIO pin numbers.) For example, the LED on the left, LED 1, is connected to GPIO 4.

Image

FIGURE 9-3 Attaching the LEDs to the status board

You can now add your own touches to the front of the board. Perhaps add photos to represent the members of your home, and decorate it to suit your style and taste.

Connecting the LEDs to the Raspberry Pi

To power each LED, you need to take the longer, positive leg that has the resistor wrapped around it and attach its jumper wire to a GPIO pin. (Any one will work fine, but I suggest using the ones in the following table.) Then take the shorter, negative leg and attach its jumper wire to a ground GPIO pin labeled GND. Figure 9-4 shows these connections. The GND pins are located at physical pins 6, 9, 14, 20, 25, 30, 34, and 39. You can use any of these.

Image

FIGURE 9-4 Connecting an LED to the Raspberry Pi

Now do the same for all your other LEDs to wire them up to the Raspberry Pi board (Figure 9-5). The following table shows which GPIO pins to use.

ITEM

GPIO

LED 1

4

LED 2

18

LED 3

24

LED 4

7

LED 5

26

Shutdown button

16

The last set of wires is for the shutdown button, which, when pressed, will power down the Raspberry Pi. Add a jumper wire to GPIO 16 and another one to a GND pin. If you need to, you can connect the LED to any of the pins, except for the 3V and 5V pins (1, 2, 4, and 17), depending on where your LEDs and Pi are positioned on the board. For example, if your Raspberry Pi is in the middle of the board, you may want to use GPIO 2, 3, 4, 14, 15, or 18 for the LEDs located to the right side and 13, 19, 26, 16, 20, or 21 for LEDs on the left. The other end of the LED is attached to one of the ground pins to complete the circuit. If you do use different GPIO numbers or add more LEDs, take note of each GPIO pin number and its corresponding LED, as you’ll need them later when you code with Python.

Image

FIGURE 9-5 Wiring up all the LEDs and the button

Attaching the Raspberry Pi

Most Raspberry Pis come with four small screw points, one in each corner of the board. These are perfect for mounting the Pi onto the status board. You can use either small screws to screw the Pi in place or adhesive glue dots to secure it. Use the screws if you want to remove the Raspberry Pi and use it for something else in the future.

TRACKING DEVICES WITH IP ADDRESSES

First, you’ll set the Pi to track your house members through their IP addresses. Take a moment to consider the enormous number of devices that use the internet: mobile phones, smart TVs, game consoles, smart watches, refrigerators, cars, tablets, and alarm systems, just to name a few. With so many devices connected, how does the correct data get to the correct device? How does the data for a video you’re streaming, for example, know to be sent to your tablet while someone else in the house is checking email or listening to music?

Well, every device connected to the internet is given an Internet Protocol (IP) address. From the outside, these addresses work similarly to zip codes: they indicate a set of devices within a certain network—your network will be your shared internet connection. From inside this network, each device is given its own unique IP address so the router knows what information to send where.

An IP address is made up of four sets of numbers: for example, 192.168.1.24. At last count, about 340 trillion trillion trillion IPv6 addresses were in use!1

You’ll use the individual IP addresses of the devices on your network to check whether each device is nearby. Because your Raspberry Pi is connected to your home network, it will have its own IP address. Let’s discover what that is.

FINDING YOUR IP ADDRESS

Open the terminal and enter the following, which should give you some information about your network:

pi@raspberrypi:- $ hostname –I

This displays the IP address of your Raspberry Pi. In Figure 9-6, my IP address is 192.168.1.171.

Image

FIGURE 9-6 Getting the Raspberry Pi’s IP address

FINDING THE IP ADDRESSES OF OTHER DEVICES

There are two methods for finding the IP addresses of the other devices on your network. The first is to use an app such as Fing from your phone or tablet, and the second is to use a program called Nmap from your Pi.

Using Fing

Fing will scan your router and network and return all the IP addresses, plus the name and the manufacturer of all connected devices. Write down this information so you can use it later in the program code. If you want to take this simpler route, download Fing to your phone or other device, and follow instructions at www.fing.io.

Using Nmap

Alternatively, you can write a small Python program on your Pi to scan and return the addresses. This has an advantage: you can copy and paste the numbers straight into the main program and not risk mistyping them. To do this, you’ll use a program called Nmap.

Installing Nmap

Nmap (Network Mapper) is a scanner used to discover devices and services on a computer network. Nmap sends a specific packet of data to the router and then analyzes the responses to build a table of information about the connected devices. From this table, the program builds a map of your network. To install Nmap, open the terminal window and enter the following:

pi@raspberrypi:- $ sudo apt install nmap

Nmap commands are executed from the terminal, so to use Python and the features of Nmap, you need to install a Python wrapper. A wrapper is a program that enables you to write Python code in the terminal to control some software. In the terminal, enter this:

pi@raspberrypi:- $ sudo pip3 install python-nmap
Writing a Program to Find the IP Addresses

Now that you have Nmap installed, you can write a Python program to search for the IP addresses of connected devices. Open IDLE and start a new Python file. Add the code in Listing 9-1 and save it. Before you run it, make sure your own phone or other device is connected to the router, because you’ll use your device as the tester for the final code.

 import nmap
 nm = nmap.PortScanner()
 data = nm.scan(hosts='192.168.1.0/24', arguments= '-sP')
   print (data['scan'])
   print ("")
 for host in nm.all_hosts():
     print ('Host : %s (%s)' % (host, nm[host].hostname()))

LISTING 9-1 Nmap scanning program

Start by importing the nmap library and then create the variable nm to hold the PortScanner() function from the nmap library. This function, as you might have guessed, scans ports!

Next, add the code to scan the router . Most routers have a generic IP address that’s standard across all of them. This line scans all IP addresses in the range from 192.168.1.0 to 192.168.1.24 and then retrieves the data that each IP address holds about the connected devices.

However, you may need to check the IP range for your particular router and change the range to reflect this. For example, your router’s IP address range may start from 192.168.0.1, or you may have configured your own custom range. If in doubt, refer to the service provider’s guidance and documentation.

Now use a for loop to cycle through all the hosts (the devices) that have been found . This will provide you with the IP address as well as the name of each device that is currently connected to the router or was previously connected (many routers keep a list of all previously connected devices).

The list you retrieve provides lots of details about the devices, so you’ll print this out to help you identify each device. Once you’ve entered and saved the program, press F5 to run it and you’ll be presented with a list of connected devices and IP addresses in the Python editor window, like the one in Listing 9-2.

Python 3.5.3
[GCC 6.3.0 20170124] on linux
Type "copyright", "credits" or "license()" for more information.
>>>
=== RESTART: /home/pi/find_ipadresses.py ===
{'192.168.1.1': {'addresses': {'ipv4': '192.168.1.1'}, 'hostnames':
[{'name': 'TestBox.cc', 'type': 'PTR'}], 'vendor': {}, 'status':
{'reason': 'syn-ack', 'state': 'up'}}, '192.164.1.xxx':
{'addresses': {'ipv4': '192.168.1.xxx'}, 'hostnames': [{'name': '',
'type': ''}], 'vendor': {}, 'status': {'reason': 'conn-refused',
'state': 'up'}}}

LISTING 9-2 The IP addresses that have been found

Copy and paste your details into a text document or a new Python file. If you paste into a Python file, remember to add a # before each line to comment it out—this will stop any errors when the program runs. Now, try to identify whom each device belongs to and note the additional information next to the device name. You might be able to make the identification from the device name, or you could quickly check who is in the house and use a process of elimination. For example, if you have two iPhone users in the house, and one phone is showing up, check the model number. If a person is out, you know that any phone that shows up is not theirs. Some users will make it easy for you by using their real name for their device name. You should also make a note of which device is yours.

Remember that in an ideal situation, the devices will be connected to the router and will return the current IP address. But IP addresses can change when the router is turned off or reset, so any devices in your home that are turned off may show up as their previous IP address. It’s best to wait until they go back online before you collect the addresses.

WRITING THE STATUS BOARD CODE

Now that you have a list of IP addresses, devices, and users, you can create the program that combines this information with the electronics in your status board to spy on who is present in your home. If you’re using a Pi Zero W, you’ll need to SSH in (see “Accessing the Raspberry Pi via SSH” on page 25) or use a remote desktop application to access your Pi. Otherwise, you could write and test the code in this section on a Raspberry Pi and then transfer its SD card to your Pi Zero W.

In Python code, you’d typically group common elements like LEDs together. Our code, though, will make more sense if you group the code by each person or device; that way, you can easily add LEDs and check for more people. That’s what you’ll do here.

This program uses the gpiozero library and the PingServer() class, which sends out pings. But what is a ping? You can think of a ping as a request that’s sent to your router. The request is made up of packets of data, represented as a string of zeros and ones, which request information from your router about all of the devices that are connected to it. The router then sends that information back to your Pi and the Python program. In this project, the data is sent back to your Raspberry Pi. You’ll use this information to find out who is around.

Setting Up and Identifying the First Device

Open your Python editor and add the code shown in Listing 9-3.

Then save it as wifi_spy.py.

 from gpiozero import PingServer, LED, Button
 from subprocess import check_call()
 from signal import pause

 def shutdown():
    check_call()(['sudo', 'poweroff'])
   
   # first device apple phone
 frank = PingServer('192.168.1.1') # hub
 led = LED(4)

LISTING 9-3 Setting up and finding the first device

First, import the required functions from the gpiozero library. You need PingServer() to retrieve the data from the router, the LED class to control the LEDs, and the Button module to add the button function to shut down the board.

You also need to import check_call() from the subprocess library . This lets you use commands in the terminal to control the Raspberry Pi, and you’ll use this to let you shut down the Pi from the terminal.

Finally, import pause from the signal library so you can keep the program running continuously .

Next, create a shutdown() function that holds the code for shutting down the Pi . This uses the check_call() command to run the command sudo poweroff, which turns off the Pi.

Now you can start detecting people! I’ve put in a comment to help keep track of each person that the device and LED in the status board refers to; you should change this comment to reflect the first device in your house.

Create a variable to hold the details of the first IP address you check . You should name the variable after the user of the device, which you figured out in “Finding the IP Addresses of Other Devices” on page 147. This variable contains the command to ping the router and the device’s IP address. In place of the IP address I’ve put here, take the first IP address from the list you got earlier using Fing or Nmap and place that in the brackets, remembering the quote marks.

The last line identifies which GPIO pin is used by this person’s LED . Each individual should have their own LED, so here Frank is assigned the LED attached to GPIO pin 4.

Finding the Rest of the Devices

Now you’ll use the same code structure to set up the variables for the other device IP addresses you want to check and assign an LED to each device. Add the lines of code from Listing 9-4 to the bottom of your program.

   # second device oneplus
   scott = PingServer('192.168.1.22') # oneplus
   led_scott = LED(18)
   
   # third device laptop 1
 liz = PingServer('192.168.1.72') # laptop 1
   led_liz = LED(24)
    
   # fourth device raspberry pi
   jenny = PingServer('192.168.1.165') # pi
   led_jenny = LED(7)
   
   # fifth device laptop 2
   jade = PingServer('192.168.1.209') # laptop 2
   led_jade = LED(26)

LISTING 9-4 Assigning LEDs to each device

As before, you create a variable to hold the results of each ping, indicating the name of the person who owns the device. Remember to replace each variable name with a name in your household, and replace each IP address with the corresponding IP address you collected earlier .

If you can’t locate enough devices, still add the code for each variable listed here and just use an IP address you already used. This will turn on multiple LEDs at once, but it will mean you can test that the wiring and the program code are working correctly. Once you have it all working, you can go back and delete or comment out those lines if you want.

Adding Delays, Responding to Data, and Adding the Button

Finally, you add the concluding section of the program code, shown in Listing 9-5. This will put a delay between the pings for each person.

You delay between each ping because pinging the router too many times will create a lot of traffic and slow the network. You might get caught! Also, a person isn’t likely to leave the house and return every second, so you can run the check once a minute.

   # check every 60 seconds
 led.source_delay = 55
   led_scott.source_delay = 56
   led_liz.source_delay = 57
   led_jenny.source_delay = 58
   led_jade.source_delay = 59
      
   # power on LEDs
 led.source = frank.values
   led_scott.source = scott.values
   led_liz.source = liz.values
   led_jenny.source = jenny.values
   led_jade.source = jade.values
      
   # GPIO 16 for shutdown
 shutdown_btn = Button(16, hold_time=2)
 shutdown_btn.when_held = shutdown
   
 pause()

LISTING 9-5 Adding delays between pings

Replace the names I’ve used here with the names you used for your variables, and then list the delay in seconds as I’ve done . If you find your network is still running slow or you want to run the checks less frequently, increase the number of seconds for the delays. For example, you could increase the delays to 300, as a user is likely to be online for a while. Note that some smartphones may appear disconnected from your network when the phone screen locks.

Next the program needs to respond to the ping data. If the IP address sent in the ping is located on the router and confirmed as live, the corresponding LED is turned on . If the IP address isn’t found, then the device isn’t found, and the LED is turned off.

Finally, you set up the button to initiate the shutdown sequence . You set this to GPIO pin 16 (if you used a different pin, make sure you put that GPIO pin number here).

The value in hold_time refers to how long the button must be held down to trigger the shutdown sequence . This program sets the time to 2 seconds so that accidentally pressing the button for a moment won’t shut down the program. (You have to hold the button down for at least 2 seconds.) The when_held checks whether the button is being pressed and runs the function to shut down the Raspberry Pi and turn off the status board if it is.

Finally, use pause() to keep the program looping forever. That concludes the main program structure and status board hardware setup!

Running the Program

Let’s give it a whirl! To check that the program code is working correctly, press F5. This will prompt you to save your program, and then it will execute. Depending on who is around and which devices are connected, you should see some of the LEDs light up.

Make sure your own device is on and connected to the router. To test whether the code is responding, turn off your device or set it to flight mode. You should see your own LED turn off! Remember that the code runs once a minute, so it might not turn off straight away.

Troubleshooting

If the status board doesn’t appear to work correctly, check for these common culprits:

  1. Are any devices connected to the router?
  2. Are your LEDs faulty?
  3. Have you wired up the LEDs correctly? (Check that the positive/negative legs are connected the correct way.)
  4. Does the LED pin number match the pin number used in the code?
  5. Are you using the right IP address for each user in your house?
  6. Is the correct LED assigned to the correct user?

SETTING UP THE CODE TO RUN AUTOMATICALLY

The last step of the project is to configure the program to run automatically so that your status board responds when the Raspberry Pi boots up. Once you have your program working and the status board functioning correctly, you can remove your monitor and attach the Raspberry Pi to the status board. Then, to start up the status board, simply plug in the power to your Raspberry Pi. To turn it off, press the shutdown button or touch the two wires together, and your Raspberry Pi will start the process of shutting down.

Using Cron to Autostart the Program

To start up your status board automatically, you need to schedule the Python program to execute on boot-up. This uses cron, a simple time-based job-scheduling tool named after the Greek word for time, chronos. This tool enables you to create rules for triggering tasks automatically at specific times. For example, you might set rules to download files every hour, run an update every day at 4 PM, or send an email at the same time each week.

You create these rules in a crontab (short for cron table) file, a simple text file that contains the task’s instructions and, most important, the time to trigger the task.

Before you add this task to the crontab file, you need to know where your wifi_spy.py program is saved in your Pi system. Unless you saved yours somewhere in particular, this location will probably be /home/pi/wifi_spy.py. Note the correct file path of wifi_spy.py, and then you’ll edit the crontab.

Open the terminal and enter this:

pi@raspberrypi:- $ crontab –e

This will open the cron console (Figure 9-7).

Image

FIGURE 9-7 The crontab

The terminal should give you three methods of editing the cron file. Select option 2 to open the nano text editor—you’ll use this because it’s the simplest.

This should open the cron file in nano, and you should see a load of code already there that looks something like Listing 9-6.

# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected)
#
# For example, you can run a backup of all your user accounts
# at 5 am every week with:
# 0 5 * * 1 tar –zcf /var/backups/home.tgz /home/
#
# For more information, see the manual pages of crontab(5) and
cron(8)
#
# m h  dom mon dow    command

LISTING 9-6 Startup code in the crontab file

Scroll to the bottom of the text and locate the black space, and right at the end add the following line of code:

@reboot python3 /home/pi/wifi_spy.py &

The command is easy to understand: it states that on rebooting the Raspberry Pi, run Python in super user mode, open the home/pi folder, and execute the program called wifi_spy.py. Make sure that you replace the filename with the name of your file, if required, and that the correct folder path is used.

The & syntax at the end of the line of code is telling cron to run your program in the background so you can still do other things with your Raspberry Pi.

Once you have checked the code you added to the crontab file and are confident that it’s correct, press CTRL-X to save and exit the file. Now, each time you boot up or reboot your Raspberry Pi, the crontab file will run and execute the status board program.

If you ever want to stop the program from automatically running, open the crontab file again from the terminal by using crontab –e, and comment out or delete the line of code that you added. Then save the file and reboot.

Rebooting to the Command Line

Because the status board is designed to run headless (without a screen or monitor), you don’t need the Raspberry Pi to boot to the desktop, as this takes longer and will use more memory and processing power than is necessary. Instead, you’ll configure the Pi to boot to the command line. Open the terminal window and enter this:

pi@raspberrypi:- $ sudo raspi-config

This should bring up the Configuration tool in your terminal, as shown in Figure 9-8. Select the third option, 3 Boot Options, and press ENTER. Then select B1 Desktop / CLI and then the B1 Console option.

Image

FIGURE 9-8 Booting to the command line option

Once this is set, use the down arrow key to select <Finish> and press ENTER. You’ll be prompted to save the config file and reboot. Select Yes, and your Pi will restart. When it boots up again, the status board program should load.

Now for a visual indicator of who is around, plug in the power source, and your status board will tell you. You may need to wait a minute or two while the Pi connects to the router. Remove the HDMI cable from your Raspberry Pi, as you’re now truly headless!

TRACKING DEVICES WITH BLUETOOTH

In this section, you’ll look at how to spy on who is around by using Bluetooth instead of Wi-Fi. Similar to the way you used IP addresses to track devices, you can use the Raspberry Pi to scan for Bluetooth data transmissions and retrieve the address of the device. This address can then be used to trigger the relevant LED on your status board.

What Is Bluetooth?

Bluetooth is the industry name for the standard range of radio waves between 2.402 and 2.480 GHz, used to enable devices to communicate wirelessly with each other over short distances of around 100–200 m. As with all technology, Bluetooth is always evolving, and the latest Bluetooth 4 technology can communicate over distances up to 200 m. Bluetooth requires little battery power, making it ideal for use on mobile devices.

Every device with Bluetooth is assigned its own unique address, with the format D2:72:F6:87:D2:8A. Because each address is unique to the device, if you get the address and know who owns each device, you can track people! From a security perspective, I recommend you remove or edit the addresses if you intend to share your program code or show others how it works.

Turning On the Raspberry Pi Bluetooth

The Raspberry Pi and Pi Zero W both come with Bluetooth hardware ready. If you have an older model Pi, you can still use this hack, but you’ll need to purchase a Bluetooth USB dongle and attach it via one of the USB ports.

To turn on Bluetooth on your Pi, locate the standard Bluetooth symbol at the top right of the desktop, click the symbol, and select Turn On Bluetooth.

The good news is that to find Bluetooth-enabled devices nearby, you don’t need to be connected to them–that would be a bit of a giveaway. If you have your own device handy, turn on and enable Bluetooth. Then return to your Pi, click the Bluetooth icon, and select the option Make Discoverable. The Bluetooth icon will start flashing green. Click the Bluetooth icon again and select the Add Devices option. A new window should open, and the Bluetooth hardware will begin scanning and searching for devices. Eventually, you’ll end up with a list of all nearby devices with Bluetooth enabled!

To collect Bluetooth addresses for the devices, you’ll write a simple Python script as you did when searching for IP addresses. The program scans for addresses, adds each address to a list, and then prints the list to the Python console. First you need to install some libraries.

To install the required Python libraries, open the terminal window and enter the following commands:

pi@raspberrypi:- $ sudo apt install bluez
pi@raspberrypi:- $ sudo apt install bluetooth libbluetooth-dev
pi@raspberrypi:- $ sudo pip3 install pybluez

When the three programs have finished downloading and installing, reboot your Raspberry Pi.

So let’s see which Bluetooth-enabled devices are in your home. Open a new Python file and copy the program in Listing 9-7. Save it as bluetooth_finder.py.

import bluetooth
from time import sleep
# find devices
print ("Searching for devices...")
nearby_devices = bluetooth.discover_devices(lookup_names = True)
sleep(10)
print ("found %d devices" % len(nearby_devices))
for addr, name in nearby_devices:
    print ("  %s - %s" % (addr, name))

LISTING 9-7 Using Bluetooth to discover devices

This code controls the Bluetooth hardware to search for nearby devices that are transmitting a Bluetooth signal. Then it creates a nicely organized list of the addresses and prints them out.

The output should look something like Listing 9-8.

Python 3.5.3 (default, Jan 19 2017, 14:11:04)
 [GCC 6.3.0 20170124] on linux
Type "copyright", "credits" or "license()" for more information.
>>>
 RESTART: /home/pi/bluetooth_finder.py
Searching for device...
found 0 devices
>>>
 RESTART: /home/pi/bluetooth_finder.py
Searching for device...
found 1 devices
  D0:57:78:87:F6:8A - DANLAPTOP

LISTING 9-8 Output from scan

Once you have the program copied, you can use it to copy and paste the addresses or write them down to use them for your status board. Remember to check which address corresponds with which device, and carry out a little testing to ensure that you have the correct address for each person.

Writing the Status Board Code

Now that you can locate Bluetooth devices and you have addresses for nearby devices, you can use these as ID codes to trigger the LEDs on your status board. This code will come in a few pieces so I can explain how each bit works. First, let’s set up some essentials.

Importing and Setting Up the LEDs

Let’s import the packages you need and set up the LEDs. Copy the program code in Listing 9-9 into a new Python file and name it bluetooth_status_board.py.

 import Bluetooth
   from bluetooth import *
    
   from gpiozero import LED, Button
   from subprocess import check_call()
   from signal import pause
   from time import sleep
    
 def shutdown():
    check_call()(['sudo', 'poweroff'])
     
   # define the LEDs
 led1 = LED(4)
   led2 = LED(18)
   led3 = LED(24)
   led4 = LED(7)
   led5 = LED(26)
   button = Button(16)

LISTING 9-9 The first part of the Bluetooth status board code

Start the program by importing the Bluetooth library, followed by the LED and Button classes to control the status LEDs and the shutdown button , respectively. Then import the subprocess library so you can use check_call() from the terminal, as you did with the Wi-Fi version. Use the sleep() function to add delays or pauses in the program.

Next, create the shutdown() function and have it use check_call() to call the command sudo shutdown from the terminal, which will tell the Raspberry Pi to power off .

Then assign each LED on the status board to a GPIO pin . You also assign the button to pin 16.

Adding the Searching Code

Now you’ll add the code to search for the Bluetooth addresses you collected! You’ll use the searching code from Listing 9-7 to find devices that have Bluetooth enabled and then turn on the status board LED if the corresponding Bluetooth address is found. Add the code in Listing 9-10 to the bottom of your current bluetooth_status_board.py file.

while True:
        # find devices
        print ("Searching for devices...")
      nearby_devices = bluetooth.discover_devices(lookup_names =
        True)
        sleep(5)
        # search for particular devices
        # person 1
      liz = bluetooth.lookup_name("C5:ED:FB:F5:BB:D7", timeout=5)
      if (liz != None):
         print ("Test 1")
         led1.on()
      else:
            led1.off()
            pass
   
        # person 2
        sarah = bluetooth.lookup_name("C5:ED:FB:F5:BB:D7", timeout=5)
        if (sarah != None):
            print ("Test 2")
            led2.on()
        else:
            led2.off()
            pass

LISTING 9-10 Searching for your first two addresses

First, add the code to detect nearby Bluetooth devices and create a list of the found addresses . This time you don’t need to print this data, so comment out the print lines.

Then search for the particular addresses you found earlier! As with the IP addresses, assign a particular Bluetooth address to a variable (using the name of the person the Bluetooth address belongs to as the variable name), look up the Bluetooth address , and add a time delay of 5 seconds to allow the devices to send and receive the required data.

The next line checks whether the address for the target associated with LED 1 (in this case, liz) has been discovered, meaning the device is present in the house. If the address has been found, the value for the variable will not be None.

The line at is for testing purposes and can be commented out of your final program. If the Bluetooth address has been found, the corresponding LED, the first LED on the status board, will be turned on using led1.on() .

If the Bluetooth address isn’t found during the search, the LED is set to off, and the program passes on to the next check .

Adding More Targets

To add more targets, copy Listing 9-11 and paste it into your program again, changing the Bluetooth address to another you found and also remembering to change the variable name and the LED number. Keep the same level of indentation on these lines of code.

        # person 3
        frank = bluetooth.lookup_name("C5:ED:FB:F5:BB:D7", timeout=5)
        if (frank != None):
            print ("Test 3")
            led3.on()
        else:
            led3.off()
            pass

LISTING 9-11 Adding more targets

If you have fewer devices, you can use fewer targets in your code, or you can use your own Bluetooth address multiple times to test that the wiring and the LEDs are functioning correctly.

Shutting Down

The concluding section of the code, shown in Listing 9-12, sets up the shutdown button.

        #shutdown button
      if button.is_pressed:
          shutdown()
        else:
            pass

LISTING 9-12 Setting up the shutdown button

Add the if button.is_pressed: code to check whether the button has been pressed . If it has, the shutdown() function will run . This will turn the status board off, and your Raspberry Pi will shut down.

This completes the code for using Bluetooth addresses to trigger your status board. Now save the program code and test that it’s working correctly. You might also want to edit the crontab file by using the instructions in “Using Cron to Autostart the Program” on page 155 so that this program runs on startup instead of the IP address finder. To ensure accuracy, run either the IP or the Bluetooth search, and not both at the same time.

Well done! You’ve used either Wi-Fi and IP addresses to track a mobile device or Bluetooth to get information about the devices that are near you. Or you may have done both! You then created a visual status board on which an LED lights up only whenever a particular device is located, meaning that the owner of the device is likely nearby. Once you’ve added pictures or written the names of the people who own each device, you now have a nice, easy way to see who is about.

WRAPPING UP

Once your status board is up and running, you may want to add features to the project. To get your inventive juices flowing, you could try some of the following:

  1. Assign different colors for each target.
  2. Add more LEDs.
  3. Make the LEDs flash.
  4. Build a bigger status board.
  5. Add a sound that plays when a device is detected.
..................Content has been hidden....................

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