Practical Python Programming for IoT: Build advanced IoT projects using a Raspberry Pi 4, MQTT, RESTful APIs, WebSockets, and Python 3

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

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. About the Author Gary Smart is a senior software engineer and an IoT and integration expert. The commencement of Gary's IT career coincided with the birth of the World Wide Web and has grown in line with the internet and emerging technologies ever since, including the rise of mobile phones and tablets, embedded technologies, SaaS and business migration to the cloud, and in recent years, the IoT revolution. Gary's practical experience includes both technical and management positions and experience in both small and large organizations, including Hewlett-Packard, Deakin University, and Pacific Hydro-Tango, boutique consulting firms, and innovative internet and IoT start-ups.

Author(s): Gary Smart
Edition: 1
Publisher: Packt Publishing
Year: 2020

Language: English
Commentary: Vector PDF
Pages: 516
City: Birmingham, UK
Tags: Multithreading; Python; Internet of Things; Asynchronous Programming; Data Visualization; Flask; Raspberry Pi; IFTTT; Networking; UART; SPI Bus; Web Servers; MQTT; Electronic Components; I²C Bus; asyncio; Electronics; Transistors; GPIO; Do-It-Yourself; Relays; Displays; LEDs; Photoresistrors; Distance Sensors; Humidity Sensors; Digital Electronics; Stepper Motors; Temperature Sensors; Flame Sensors; RESTful API; Pulse-Width Modulation; Servo Motors; Sound; ThingSpeak

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