Book Image

Practical Python Programming for IoT

By : Gary Smart
Book Image

Practical Python Programming for IoT

By: Gary Smart

Overview of this book

The age of connected devices is here, be it fitness bands or smart homes. It's now more important than ever to understand how hardware components interact with the internet to collect and analyze user data. The Internet of Things (IoT), combined with the popular open source language Python, can be used to build powerful and intelligent IoT systems with intuitive interfaces. This book consists of three parts, with the first focusing on the "Internet" component of IoT. You'll get to grips with end-to-end IoT app development to control an LED over the internet, before learning how to build RESTful APIs, WebSocket APIs, and MQTT services in Python. The second part delves into the fundamentals behind electronics and GPIO interfacing. As you progress to the last part, you'll focus on the "Things" aspect of IoT, where you will learn how to connect and control a range of electronic sensors and actuators using Python. You'll also explore a variety of topics, such as motor control, ultrasonic sensors, and temperature measurement. Finally, you'll get up to speed with advanced IoT programming techniques in Python, integrate with IoT visualization and automation platforms, and build a comprehensive IoT project. By the end of this book, you'll be well-versed with IoT development and have the knowledge you need to build sophisticated IoT systems using Python.
Table of Contents (20 chapters)
1
Section 1: Programming with Python and the Raspberry Pi
6
Section 2: Practical Electronics for Interacting with the Physical World
9
Section 3: IoT Playground - Practical Examples to Interact with the Physical World

Installing Python GPIO packages with pip

In this section, we learn how to install and manage Python packages in a Python virtual environment you created and explored in the previous section. A Python package (or library if you prefer that term) allows us to extend the core Python language with new features and functionality. 

We will need to install many different packages throughout this book, however, for starters and to explore and learn the basic concepts related to package installation and management, we will be installing two common GPIO-related packages in this section that we will use throughout this book. These two packages are the following:

  • The GPIOZero library, an entry-level and easy to use GPIO library for controlling simple electronics
  • The PiGPIO library, an advanced GPIO library with many features for more complex electronic interfacing

In the Python ecosystem, package management is done with the pip command (pip stands for Python installs packages). The official public package repository that pip queries is known as the Python Package Index, or simply PyPi, and it is available for browsing on the web at https://pypi.org.

Similarly to python and python3, there is pip and pip3. pip (without the number) will be the default pip command that is matched to the default python command in a given virtual environment.

There will be code examples in this book where we will be interacting with your Raspberry Pi's GPIO pins, so we need to install a Python package (or two) so that your Python code can work with your Raspberry Pi's GPIO pins. For now, we are just going to check for and install two GPIO-related packages. In Chapter 2Getting Started with Python and IoT, and Chapter 5, Connecting Your Raspberry Pi to the Physical World, we will cover these GPIO packages and other alternatives in greater detail.

In your chapter01 source code folder, you will find a file named gpio_pkg_check.py, which is replicated in the following. We will use this file as the basis to learn about pip and package management in the context of a Python virtual environment. This script simply reports the availability of a Python package depending on whether using import succeeds or raises an exception:

"""
Source File: chapter01/gpio_pkg_check.py
"""
try:
import gpiozero
print('GPIOZero Available')
except:
print('GPIOZero Unavailable. Install with "pip install gpiozero"')

try:
import pigpio
print('pigpio Available')
except:
print('pigpio Unavailable. Install with "pip install pigpio"')

Let's check for the availability of GPIO packages using gpio_pkg_check.py and with pip. I'll kill the suspense by telling you that they're not going to be available in your freshly-created virtual environment (yet), however, we are going to install them!

Note: They are already installed at the system level if you want to check yourself by running this script outside of your virtual environment.

The following steps will walk us through the process of upgrading pip, exploring the tool's options, and installing packages:

  1. As the first step, we will upgrade the pip tool. In a Terminal window, run the following command, remembering that all commands that follow must be performed in an activated virtual environment—meaning you should see the text (venv) in the Terminal prompt:
(venv) $ pip install --upgrade pip
...output truncated...

The preceding upgrade command may take a minute or two complete and will potentially output a lot of text to the Terminal.

Are you facing pip problems? If you're getting a sea of red errors and exceptions when trying to install a package with pip, try upgrading the pip version as a first step using pip install --upgrade pip. It is a recommended first step after creating a fresh Python virtual environment to upgrade pip.
  1. With pip now upgraded, we can see what Python packages are already installed in our virtual environment using the pip list command:
(venv) $ pip list
pip (9.0.1)
pkg-resources (0.0.0)
setuptools (33.1.1)

What we see in the preceding are the default Python packages in our fresh virtual environment. Do not worry if the exact package list or version numbers do not match exactly with the example.

  1. Run our Python script with the python gpio_pkg_check.py command and observe that our GPIO packages are not installed:
(venv) $ python gpio_pkg_check.py
GPIOZero Unavailable. Install with "pip install gpiozero"
pigpio Unavailable. Install with "pip install pigpio"
  1. To install our two required GPIO packages, we use the pip install command as shown in the following example:
(venv) $ pip install gpiozero pigpio
Collecting gpiozero...
... output truncated ...
  1. Now, run the pip list command again; we will see these new packages are now installed in our virtual environment:
(venv) $ pip list
colorzero (1.1)
gpiozero (1.5.0) # GPIOZero
pigpio (1.42) # PiGPIO
pip (9.0.1)
pkg-resources (0.0.0)
setuptools (33.1.1)

You may have noticed that there is a package called colorzero (this is a color manipulation library) that we did not install. gpiozero (version 1.5.0) has a dependency on colorzero, so pip has installed it for us automatically.

  1. Re-run python gpio_pkg_check.py and we now see that our Python modules are available for import:
(venv) $ python gpio_pkg_check.py
GPIOZero Available
pigpio Available

Great! We now have a virtual environment with two GPIO packages installed. As you work on Python projects, you will inevitably install more and more packages and want to keep track of them.

  1. Take a snapshot of the packages you have previously installed with the pip freeze command:
(venv) $ pip freeze > requirements.txt

The preceding example freezes all installed packages into a file named requirements.txt, which is a common filename to use for this purpose.

  1. Look inside the requirements.txt file and you will see all of the Python packages listed together with their version numbers:
(venv) $ cat requirements.txt
colorzero==1.1
gpiozero==1.5.0
pigpio==1.42
pkg-resources==0.0.0

In the future, if you move your Python project to another machine or a new virtual environment, you can use your requirement.txt file to install all of your captured packages in one go using the pip install -r requirements.txt command.

Our requirements.txt example shows we have installed GPIOZero version 1.5.0, the current version at the time of writing. This version has a dependency on ColorZero version 1.1. It is possible that different (past or future) versions of GPIOZero may have different dependencies than those shown in our example, so your own requirements.txt file when performing the example exercise may be different.

We've now completed the basic installation life cycle of Python packages using pip. Note that whenever you install new packages with pip install, you also need to re-run pip freeze > requirements.txt to capture the new packages and their dependencies.

To finish our exploration of pip and package management, here are a few other common pip commands:

# Remove a package
(venv) $ pip uninstall <package name>

# Search PyPi for a package (or point your web browser at https://pypi.org)
(venv) $ pip search <query text>

# See all pip commands and options (also see Further Reading at the end of the chapter).
(venv) $ pip --help

Congratulations! We've reached a milestone and covered the essential virtual environment principles that you can use for any Python project, even ones that are not Raspberry Pi related! 

During your Python journey, you will also come across other package installers and tools named easy_install and setuptools. Both have their uses; however, it's pip that you will rely on most of the time.

Now that we have seen how to create a virtual environment and install packages, let's take a look at a typical Python project folder structure such as ~/pyiot/chapter01 and discover what lies beneath the venv folder.