Practical Python Programming for IoT

Book description

Leverage Python and Raspberry Pi to create complex IoT applications capable of creating and detecting movement and measuring distance, light, and a host of other environmental conditions

Key Features

  • Learn the fundamentals of electronics and how to integrate them with a Raspberry Pi
  • Understand how to build RESTful APIs, WebSocket APIs, and MQTT-based applications
  • Explore alternative approaches to structuring IoT applications with Python

Book Description

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.

What you will learn

  • Understand electronic interfacing with Raspberry Pi from scratch
  • Gain knowledge of building sensor and actuator electronic circuits
  • Structure your code in Python using Async IO, pub/sub models, and more
  • Automate real-world IoT projects using sensor and actuator integration
  • Integrate electronics with ThingSpeak and IFTTT to enable automation
  • Build and use RESTful APIs, WebSockets, and MQTT with sensors and actuators
  • Set up a Raspberry Pi and Python development environment for IoT projects

Who this book is for

This IoT Python book is for application developers, IoT professionals, or anyone interested in building IoT applications using the Python programming language. It will also be particularly helpful for mid to senior-level software engineers who are experienced in desktop, web, and mobile development, but have little to no experience of electronics, physical computing, and IoT.

Table of contents

  1. Title Page
  2. Copyright and Credits
    1. Practical Python Programming for IoT
  3. About Packt
    1. Why subscribe?
  4. Contributors
    1. About the author
    2. About the reviewer
    3. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Download the example code files
    5. Code in Action
    6. Download the color images
    7. Conventions used
    8. Get in touch
    9. Reviews
  6. Section 1: Programming with Python and the Raspberry Pi
  7. Setting Up your Development Environment
    1. Technical requirements
    2. Understanding your Python installation
    3. Setting up a Python virtual environment
    4. Installing Python GPIO packages with pip
    5. Anatomy of a virtual environment
    6. Alternative methods of executing a Python script
    7. Using sudo within virtual environments
    8. Executing Python scripts outside of their virtual environments
    9. Running a Python script at boot
    10. Configuring the GPIO interface on our Raspberry Pi
    11. Configuring the PiGPIO daemon
    12. Summary
    13. Questions
    14. Further reading
  8. Getting Started with Python and IoT
    1. Technical requirements
    2. Creating a breadboard prototype circuit
    3. Understanding the breadboard
    4. Positioning and connecting the push button
    5. Positioning and connecting the LED
    6. Positioning and connecting the resistor
    7. Reading an electronic schematic diagram
    8. Reading the push button schematic connection
    9. Reading the LED and resistor schematic connection
    10. Introducing ground connections and symbols
    11. Exploring two ways to flash an LED in Python
    12. Blinking with GPIOZero
    13. Imports
    14. Pin Factory configuration
    15. Blinking the LED
    16. Blinking with PiGPIO
    17. Imports
    18. PiGPIO and pin configuration
    19. Blinking the LED
    20. Comparing the GPIOZero and PiGPIO examples
    21. Exploring two ways to integrate a push button in Python
    22. Responding to a button press with GPIOZero
    23. Imports
    24. Button pressed handler
    25. Button configuration
    26. Preventing the main thread from terminating
    27. Responding to a button press with PiGPIO
    28. Button pin configuration
    29. Button pressed handler
    30. Creating your first IoT program
    31. Running and testing the Python server
    32. Understanding the server code
    33. Imports
    34. Variable definitions
    35. The resolve_thing_name() method
    36. The get_lastest_dweet() method
    37. The poll_dweets_forever() method
    38. The process_dweet() method
    39. The main program entry point
    40. Extending your IoT program
    41. Implementing a dweeting button
    42. PiGPIO LED as a class
    43. Summary
    44. Questions 
    45. Further reading
  9. Networking with RESTful APIs and Web Sockets Using Flask
    1. Technical requirements
    2. Introducing the Flask microservices framework
    3. Creating a RESTful API service with Flask-RESTful
    4. Running and testing the Python server
    5. Understanding the server code
    6. Imports
    7. Flask and Flask-RESTful API instance variables
    8. Global variables
    9. The init_led() method
    10. Serving a web page
    11. The LEDControl class
    12. The get() class method
    13. The post() class method
    14. LEDController registration and starting the server
    15. Introduction to PWM
    16. Adding a RESTful API client web page
    17. Understanding the client-side code
    18. JavaScript imports
    19. The getState() function
    20. The postUpdate() function
    21. The updateControls() function
    22. Registering event handlers with jQuery
    23. The web page HTML
    24. Creating a Web Socket service with Flask-SocketIO
    25. Running and testing the Python server
    26. Server code walkthrough
    27. Imports
    28. Flask and Flask-RESTful API instance variables
    29. Serving a web page
    30. Connecting and disconnecting handlers
    31. LED handler
    32. Starting the server
    33. Adding a Web Socket client web page
    34. Understanding the client-side code
    35. Imports
    36. Socket.IO connect and disconnect handlers
    37. The on LED handler
    38. The document ready function
    39. The web page HTML
    40. Comparing the RESTful API and Web Socket servers
    41. Summary
    42. Questions
    43. Further reading
  10. Networking with MQTT, Python, and the Mosquitto MQTT Broker
    1. Technical requirements
    2. Installing the Mosquitto MQTT broker
    3. Learning MQTT by example
    4. Publishing and subscribing MQTT messages
    5. Exploring MQTT topics and wildcards
    6. Applying Quality of Service to messages
    7. Retaining messages for later delivery
    8. Publishing a retained message
    9. Creating durable connections
    10. Saying goodbye with a Will
    11. Using MQTT broker services
    12. Introducing the Python Paho-MQTT client library
    13. Controlling an LED with Python and MQTT
    14. Running the LED MQTT example
    15. Understanding the code
    16. Imports
    17. Global variables
    18. The set_led_level(data) method
    19. The on_connect() and on_disconnect() MQTT callback methods
    20. The on_message() MQTT callback method
    21. The init_mqtt() method
    22. Main entry point
    23. Building a web-based MQTT client
    24. Understanding the code
    25. Imports
    26. Global variables
    27. The Paho JavaScript MQTT client
    28. Connecting to the broker
    29. The onConnectionLost and onMessageArrived handler methods
    30. JQuery document ready function
    31. Summary
    32. Questions
    33. Further reading
  11. Section 2: Practical Electronics for Interacting with the Physical World
  12. Connecting Your Raspberry Pi to the Physical World
    1. Technical requirements
    2. Understanding Raspberry Pi pin numbering
    3. Exploring popular Python GPIO libraries
    4. Reviewing GPIOZero – simple interfacing for beginners
    5. Reviewing RPi.GPIO – a low-level GPIO for beginners
    6. Reviewing Circuit Python and Blinka – interfacing for complex devices
    7. Reviewing PiGPIO – a low-level GPIO library
    8. Exploring remote GPIO with PiGPIO (and GPIOZero)
    9. Reviewing SPIDev and SMBus – dedicated SPI and I2C libraries
    10. Why PiGPIO?
    11. Exploring Raspberry Pi electronic interfacing options
    12. Understanding digital IO
    13. Understanding analog IO
    14. Understanding Pulse-Width Modulation
    15. Creating PWM signals
    16. Understanding SPI, I2C, and 1-wire interfaces
    17. Understanding the serial / UART protocol
    18. Interfacing with an analog-to-digital converter
    19. Building the ADS1115 ADC circuit
    20. Making sure the ADS1115 is connected to your Raspberry Pi
    21. Reading analog input with the ADS1115
    22. Understanding the code
    23. Imports
    24. ADS1115 setup and configuration
    25. Global variables
    26. Program entry point
    27. Using PWM to control an LED
    28. Understanding the code
    29. Global variables
    30. Range mapping function
    31. Generating the PWM signal
    32. Visually exploring PWM with PiScope
    33. Visualizing software and hardware-timed PWM
    34. Summary
    35. Questions
    36. Further reading
  13. Electronics 101 for the Software Engineer
    1. Technical requirements
    2. Fitting out your workshop
    3. Buying electronic modules and components
    4. Purchasing lose components
    5. Purchasing open source hardware modules
    6. Keeping your Raspberry Pi safe
    7. Three ways electronic components fail
    8. Electronics interfacing principles for GPIO control
    9. Ohm's Law and power
    10. Kirchhoff's circuit laws
    11. Why are we using a 200 Ohm resistor for the LED circuit?
    12. Calculating the resistor value
    13. Factoring in the Raspberry Pi's current limits
    14. Calculating the resistor's power dissipation
    15. Exploring digital electronics
    16. Digital output
    17. Digital input
    18. Using pull-up and pull-down resistors
    19. The resistor solution
    20. The code solution
    21. Exploring analog electronics
    22. Analog output
    23. Analog input
    24. Voltage dividers
    25. Understanding logic-level conversion
    26. Voltage dividers as logic-level converters
    27. Logic-level converter ICs and modules
    28. Comparing voltage dividers and logic-level converters
    29. Summary
    30. Questions
    31. Further reading
  14. Section 3: IoT Playground - Practical Examples to Interact with the Physical World
  15. Turning Things On and Off
    1. Technical requirements
    2. Exploring a relay driver circuit
    3. Determining a load's voltage and current
    4. Measuring the current requirement of a DC motor
    5. Measuring the current requirement of a relay and LED
    6. Using an optocoupler as a switch
    7. Building the optocoupler circuit
    8. Controlling the optocoupler with Python
    9. Using a transistor as a switch
    10. Building the MOSFET circuit
    11. Controlling the MOSFET with Python
    12. Using a relay as a switch
    13. Building the relay driver circuit
    14. Controlling the Relay Driver Circuit with Python
    15. Summary
    16. Questions
    17. Further reading
  16. Lights, Indicators, and Displaying Information
    1. Technical requirements
    2. Making color with an RGB LED and PWM
    3. Creating the RGB LED circuit
    4. Running and exploring the RGB LED code
    5. Controlling a multi-color APA102 LED strip with SPI
    6. Creating the APA102 circuit
    7. Powering the APA102 circuit
    8. Configuring and running the APA102 LED strip code
    9. APA102 LED strip code walkthrough
    10. Discussion of APA102 and the SPI interface
    11. APA102 LED strip troubleshooting tips
    12. Using an OLED display
    13. Connecting the OLED display
    14. Verifying whether the OLED display is connected
    15. Configuring and running the OLED example
    16. OLED code walkthrough
    17. Making sound with buzzers and PWM
    18. Building the RTTTL circuit
    19. Running the RTTTL music example
    20. Summary
    21. Questions
    22. Further reading
  17. Measuring Temperature, Humidity, and Light Levels
    1. Technical requirements
    2. Measuring temperature and humidity
    3. Creating the DHT11/DHT22 circuit
    4. Running and exploring the DHT11/DHT22 code
    5. Detecting light
    6. Creating an LDR light-detecting circuit
    7. Running the LDR example code
    8. LDR code walkthrough
    9. LDR configuration summary
    10. Detecting moisture
    11. Comparing detection options
    12. Summary
    13. Questions
  18. Movement with Servos, Motors, and Steppers
    1. Technical requirements
    2. Using PWM to rotate a servo
    3. Connecting a servo to your Raspberry Pi
    4. How a servo is controlled using PWM
    5. Running and exploring the servo code
    6. Different types of servos
    7. Using an H-Bridge IC to control a motor
    8. Building the motor driver circuit
    9. Running the example H-Bridge code to control a motor
    12. Introduction to stepper motor control
    13. Connecting the stepper motor to the L293D circuit
    14. Running and exploring the stepper motor code
    15. Summary
    16. Questions
  19. Measuring Distance and Detecting Movement
    1. Technical requirements
    2. Detecting movement with a PIR sensor
    3. Creating the PIR sensor circuit
    4. Running and exploring the PIR sensor code
    5. Measuring distance with an ultrasonic sensor
    6. How an ultrasonic distance sensor works
    7. HC-SR04 distance measurement process
    8. Building the HC-SR04 circuit
    9. Running and exploring the HC-SR04 example code
    10. Detecting movement and distance with Hall-effect sensors
    11. Creating a Hall-effect sensor circuit
    12. Running and exploring the Hall-effect sensor code
    13. Summary
    14. Questions
  20. Advanced IoT Programming Concepts - Threads, AsyncIO, and Event Loops
    1. Technical requirements
    2. Building and testing our circuit
    3. Building the reference circuit
    4. Running the examples
    5. Exploring the event-loop approach
    6. Exploring a threaded approach
    7. Exploring the publisher-subscriber alternative
    8. Exploring an AsyncIO approach
    9. An asynchronous experiment
    10. Summary
    11. Questions
    12. Further reading
  21. IoT Visualization and Automation Platforms
    1. Technical requirements
    2. Triggering an IFTTT Applet from your Raspberry Pi
    3. Creating the temperature monitoring circuit
    4. Creating and configuring an IFTTT Applet
    5. Triggering an IFTTT Webhook
    6. Triggering an IFTTT Applet in Python
    7. Actioning your Raspberry Pi from an IFTTT Applet
    8. Method 1 – using the service as an intermediary
    9. Method 2 – creating a Flask-RESTful service
    10. Creating the LED circuit
    11. Running the IFTTT and LED Python program
    12. Creating the IFTTT Applet
    13. Controlling the LED from an email
    14. IFTTT troubleshooting
    15. Visualizing data with the ThingSpeak platform
    16. Configuring the ThinkSpeak platform
    17. Configuring and running the ThinkSpeak Python program
    18. Other IoT and automation platforms for further exploration
    19. Zapier
    20. IFTTT platform
    21. ThingsBoard IoT platform
    22. Home Assistant
    23. Amazon Web Services (AWS)
    24. Microsoft Azure, IBM Watson, and Google Cloud
    25. Summary
    26. Questions
  22. Tying It All Together - An IoT Christmas Tree
    1. Technical requirements
    2. Overview of the IoT Christmas tree
    3. Building the IoTree circuit
    4. Three IoTree service programs
    5. Configuring, running, and using the Tree API service
    6. Configuring the Tree API service
    7. Running the Tree API service
    8. Configuring, running, and using the Tree MQTT service
    9. Configuring the Tree MQTT service
    10. Running the Tree MQTT service program
    11. Integrating the IoTree with
    12. Configuring the Tree MQTT service
    13. Running the dweet integration service program
    14. Integrating with email and Google Assistant via IFTTT
    15. Integration with email
    16. Integration with Google Assistant
    17. Ideas and suggestions to extend your IoTree
    18. Summary
    19. Questions
  23. Assessments
    1. Chapter 1
    2. Chapter 2
    3. Chapter 3
    4. Chapter 4
    5. Chapter 5
    6. Chapter 6
    7. Chapter 7
    8. Chapter 8
    9. Chapter 9
    10. Chapter 10
    11. Chapter 11
    12. Chapter 12 
    13. Chapter 13
    14. Chapter 14
  24. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

Product information

  • Title: Practical Python Programming for IoT
  • Author(s): Gary Smart
  • Release date: November 2020
  • Publisher(s): Packt Publishing
  • ISBN: 9781838982461