Internet of Things with Python
()
About this ebook
Interact with the world and rapidly prototype IoT applications using Python
About This Book- Rapidly prototype even complex IoT applications with Python and put them to practical use
- Enhance your IoT skills with the most up-to-date applicability in the field of wearable tech, smart environments, and home automation
- Interact with hardware, sensors, and actuators and control your DIY IoT projects through Python
The book is ideal for Python developers who want to explore the tools in the Python ecosystem in order to build their own IoT applications and work on IoT-related projects. It is also a very useful resource for developers with experience in other programming languages that want to easily prototype IoT applications with the Intel Galileo Gen 2 board.
What You Will Learn- Prototype and develop IoT solutions from scratch with Python as the programming language
- Develop IoT projects with Intel Galileo Gen 2 board along with Python
- Work with the different components included in the boards using Python and the MRAA library
- Interact with sensors, actuators, and shields
- Work with UART and local storage
- Interact with any electronic device that supports the I2C bus
- Allow mobile devices to interact with the board
- Work with real-time IoT and cloud services
- Understand Big Data and IoT analytics
Internet of Things (IoT) is revolutionizing the way devices/things interact with each other. And when you have IoT with Python on your side, you'll be able to build interactive objects and design them.
This book lets you stay at the forefront of cutting-edge research on IoT. We'll open up the possibilities using tools that enable you to interact with the world, such as Intel Galileo Gen 2, sensors, and other hardware. You will learn how to read, write, and convert digital values to generate analog output by programming Pulse Width Modulation (PWM) in Python. You will get familiar with the complex communication system included in the board, so you can interact with any shield, actuator, or sensor.
Later on, you will not only see how to work with data received from the sensors, but also perform actions by sending them to a specific shield. You'll be able to connect your IoT device to the entire world, by integrating WiFi, Bluetooth, and Internet settings. With everything ready, you will see how to work in real time on your IoT device using the MQTT protocol in python.
By the end of the book, you will be able to develop IoT prototypes with Python, libraries, and tools.
Style and approachThis book takes a tutorial-like approach with mission critical chapters. The initial chapters are introductions that set the premise for useful examples covered in later chapters.
Gastón C. Hillar
Gaston C. Hillar has been working with computers since he was eight. He began programming with the legendary Texas TI-99/4A and Commodore 64 home computers in the early 80s. He has a Bachelor degree in Computer Science, graduated with honors, and an MBA (Master in Business Administration), graduated with an outstanding thesis. He worked as developer, architect, and project manager for many companies in Buenos Aires, Argentina. Now, he is an independent IT consultant and a freelance author always looking for new adventures around the world. He also works with electronics (he is an electronics technician). He is always researching about new technologies and writing about them. He owns an IT and electronics laboratory with many servers, monitors, and measuring instruments. Gaston write the C# 2008 and 2005 Threaded Programming: Beginner's Guide also published by Packt. He is also the author of more than 40 books in Spanish about computer science, modern hardware, programming, systems development, software architecture, business applications, balanced scorecard applications, IT project management, the Internet, and electronics. He contributes to Dr. Dobb's Go Parallel programming portal http://www.ddj.com/go-parallel/ and he is a guest blogger at Intel Software Network http://software.intel.com He usually writes articles for Spanish magazines Mundo Linux, Solo Programadores and Resistor.
Read more from Gastón C. Hillar
Building RESTful Python Web Services Rating: 5 out of 5 stars5/5Learning Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsHands-On MQTT Programming with Python: Work with the lightweight IoT protocol in Python Rating: 0 out of 5 stars0 ratingsMQTT Essentials - A Lightweight IoT Protocol Rating: 0 out of 5 stars0 ratingsC# 2008 and 2005 Threaded Programming: Beginner's Guide Rating: 0 out of 5 stars0 ratingsJavaScript : Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsMicrosoft Silverlight 4 and SharePoint 2010 Integration Rating: 0 out of 5 stars0 ratingsHands-On RESTful Python Web Services: Develop RESTful web services or APIs with modern Python 3.7 Rating: 0 out of 5 stars0 ratingsProfessional Parallel Programming with C#: Master Parallel Extensions with .NET 4 Rating: 3 out of 5 stars3/5Object–Oriented Programming with Swift 2 Rating: 0 out of 5 stars0 ratingsJava 9 with JShell: Introducing the full range of Java 9's new features via JShell Rating: 0 out of 5 stars0 ratingsGuide to NoSQL with Azure Cosmos DB: Work with the massively scalable Azure database service with JSON, C#, LINQ, and .NET Core 2 Rating: 0 out of 5 stars0 ratingsLearn Web Development with Python: Get hands-on with Python Programming and Django web development Rating: 0 out of 5 stars0 ratingsSwift 3 Object-Oriented Programming - Second Edition Rating: 0 out of 5 stars0 ratingsDjango RESTful Web Services: The easiest way to build Python RESTful APIs and web services with Django Rating: 0 out of 5 stars0 ratings
Related to Internet of Things with Python
Related ebooks
Internet of Things with Python Rating: 0 out of 5 stars0 ratingsSmart Internet of Things Projects Rating: 4 out of 5 stars4/5Internet of Things Programming Projects: Build exciting IoT projects using Raspberry Pi 5, Raspberry Pi Pico, and Python Rating: 0 out of 5 stars0 ratingsRaspberry Pi IoT Projects: Prototyping Experiments for Makers Rating: 0 out of 5 stars0 ratingsIntel Galileo Essentials Rating: 0 out of 5 stars0 ratingsHands-On Internet of Things with MQTT: Build connected IoT devices with Arduino and MQ Telemetry Transport (MQTT) Rating: 0 out of 5 stars0 ratingsInternet of Things with Arduino Blueprints Rating: 0 out of 5 stars0 ratingsIntel Galileo Blueprints Rating: 0 out of 5 stars0 ratingsInternet of Things with Raspberry Pi 3: Leverage the power of Raspberry Pi 3 and JavaScript to build exciting IoT projects Rating: 0 out of 5 stars0 ratingsIntel Edison Projects: Build exciting IoT projects with Intel Edison Rating: 0 out of 5 stars0 ratingsLearn IoT Programming Using Node-RED: Begin to Code Full Stack IoT Apps and Edge Devices with Raspberry Pi, NodeJS, and Grafana Rating: 0 out of 5 stars0 ratingsLearning BeagleBone Python Programming Rating: 0 out of 5 stars0 ratingsInternet of Things Programming Projects: Build modern IoT solutions with the Raspberry Pi 3 and Python Rating: 0 out of 5 stars0 ratingsSensor Projects with Raspberry Pi: Internet of Things and Digital Image Processing Rating: 0 out of 5 stars0 ratingsInternet of Things with Intel Galileo Rating: 0 out of 5 stars0 ratingsDeveloping IoT Projects with ESP32: Automate your home or business with inexpensive Wi-Fi devices Rating: 0 out of 5 stars0 ratingsHands-On Internet of Things with Blynk: Build on the power of Blynk to configure smart devices and build exciting IoT projects Rating: 0 out of 5 stars0 ratingsHands-On Industrial Internet of Things: Create a powerful Industrial IoT infrastructure using Industry 4.0 Rating: 0 out of 5 stars0 ratingsEnterprise Internet of Things Handbook: Build end-to-end IoT solutions using popular IoT platforms Rating: 0 out of 5 stars0 ratingsAndroid Things Quick Start Guide: Build your own smart devices using the Android Things platform Rating: 0 out of 5 stars0 ratingsBeagleBone By Example Rating: 0 out of 5 stars0 ratingsLearning JavaScript Robotics Rating: 3 out of 5 stars3/5Arduino Electronics Blueprints Rating: 4 out of 5 stars4/5Raspberry Pi Home Automation with Arduino - Second Edition Rating: 0 out of 5 stars0 ratingsData Engineering with Python: Work with massive datasets to design data models and automate data pipelines using Python Rating: 0 out of 5 stars0 ratingsRaspberry Pi LED Blueprints Rating: 0 out of 5 stars0 ratingsMastering BeagleBone Robotics Rating: 5 out of 5 stars5/5Arduino Android Blueprints Rating: 0 out of 5 stars0 ratingsHands-On Blockchain for Python Developers: Gain blockchain programming skills to build decentralized applications using Python Rating: 0 out of 5 stars0 ratings
Computers For You
Elon Musk Rating: 4 out of 5 stars4/5Standard Deviations: Flawed Assumptions, Tortured Data, and Other Ways to Lie with Statistics Rating: 4 out of 5 stars4/5The Innovators: How a Group of Hackers, Geniuses, and Geeks Created the Digital Revolution Rating: 4 out of 5 stars4/5How to Create Cpn Numbers the Right way: A Step by Step Guide to Creating cpn Numbers Legally Rating: 4 out of 5 stars4/5The ChatGPT Millionaire Handbook: Make Money Online With the Power of AI Technology Rating: 4 out of 5 stars4/5Alan Turing: The Enigma: The Book That Inspired the Film The Imitation Game - Updated Edition Rating: 4 out of 5 stars4/5The Invisible Rainbow: A History of Electricity and Life Rating: 5 out of 5 stars5/5Deep Search: How to Explore the Internet More Effectively Rating: 5 out of 5 stars5/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5Slenderman: Online Obsession, Mental Illness, and the Violent Crime of Two Midwestern Girls Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsUncanny Valley: A Memoir Rating: 4 out of 5 stars4/5Mastering ChatGPT: 21 Prompts Templates for Effortless Writing Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5An Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5Procreate for Beginners: Introduction to Procreate for Drawing and Illustrating on the iPad Rating: 5 out of 5 stars5/5Learning the Chess Openings Rating: 5 out of 5 stars5/5CompTIA IT Fundamentals (ITF+) Study Guide: Exam FC0-U61 Rating: 0 out of 5 stars0 ratingsCompTIA Security+ Get Certified Get Ahead: SY0-701 Study Guide Rating: 5 out of 5 stars5/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Ultimate Guide to Mastering Command Blocks!: Minecraft Keys to Unlocking Secret Commands Rating: 5 out of 5 stars5/5The Professional Voiceover Handbook: Voiceover training, #1 Rating: 5 out of 5 stars5/5Tor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5
Reviews for Internet of Things with Python
0 ratings0 reviews
Book preview
Internet of Things with Python - Gastón C. Hillar
Table of Contents
Internet of Things with Python
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Understanding and Setting up the Base IoT Hardware
Understanding the Intel Galileo Gen 2 board and its components
Recognizing the Input/Output and the Arduino 1.0 pinout
Recognizing additional expansion and connectivity capabilities
Understanding the buttons and the LEDs
Checking and upgrading the board's firmware
Test your knowledge
Summary
2. Working with Python on Intel Galileo Gen 2
Setting up the board to work with Python as the programming language
Retrieving the board's assigned IP address
Connecting to the board's operating system
Installing and upgrading the necessary libraries to interact with the board
Installing pip and additional libraries
Invoking the Python interpreter
Test your knowledge
Summary
3. Interacting with Digital Outputs with Python
Turning on and off an onboard component
Prototyping with breadboards
Working with schematics to wire digital outputs
Counting from 1 to 9 with LEDs, Python code and the mraa library
Taking advantage of object-oriented code to control digital outputs
Improving our object-oriented code to provide new features
Isolating the pin numbers to improve wirings
Controlling digital outputs with the wiring-x86 library
Test your knowledge
Summary
4. Working with a RESTful API and Pulse Width Modulation
Printing numbers in LEDs with a RESTful API
Composing and sending HTTP requests
Wiring pins with PWM capabilities
Using PWM to generate analog values
Generating analog values via HTTP requests
Preparing the RESTful API for Web application requirements
Using PWM plus a RESTful API to set colors for an RGB LED
Controlling PWM with the wiring-x86 library
Test your knowledge
Summary
5. Working with Digital Inputs, Polling and Interrupts
Understanding pushbuttons and pullup resistors
Wiring digital input pins with pushbuttons
Reading pushbutton statuses with digital inputs and the mraa library
Reading pushbutton statuses and running a RESTful API
Reading digital inputs with the wiring-x86 library
Using interrupts to detect pressed pushbuttons
Test your knowledge
Summary
6. Working with Analog Inputs and Local Storage
Understanding the analog inputs
Wiring an analog input pin with a voltage source
Measuring voltage with analog inputs and the mraa library
Wiring a photoresistor to an analog input pin
Determining the darkness level with analog inputs and the mraa library
Firing actions when the environment light changes
Controlling analog inputs with the wiring-x86 library
Logging to files in the local storage
Working with USB attached storage
Test your knowledge
Summary
7. Retrieving Data from the Real World with Sensors
Understanding sensors and their connection types
Working with accelerometers
Wiring an analog accelerometer to the analog input pins
Measuring three axis acceleration with an analog accelerometer
Wiring a digital accelerometer to the I2C bus
Measuring three axis acceleration with a digital accelerometer
Using the I2C bus to control a digital accelerometer with the mraa library
Wiring an analog temperature sensor
Measuring ambient temperature with an analog sensor
Wiring a digital temperature and humidity sensor to the I2C bus
Measuring temperature and humidity with a digital sensor
Test your knowledge
Summary
8. Displaying Information and Performing Actions
Understanding LCD displays and their connection types
Wiring an LCD RGB backlight to the I2C bus
Displaying text on an LCD display
Wiring an OLED dot matrix to the I2C bus
Displaying text on an OLED display
Wiring a servo motor
Positioning a shaft to indicate a value with a servo motor
Test your knowledge
Summary
9. Working with the Cloud
Publishing data to the cloud with dweepy
Building a web-based dashboard with Freeboard
Sending and receiving data in real-time through Internet with PubNub
Publishing messages with commands through the PubNub cloud
Working with bi-directional communications
Publishing messages to the cloud with a Python PubNub client
Using MQTT with Mosquitto and Eclipse Paho
Publishing messages to a Mosquitto broker with a Python client
Test your knowledge
Summary
10. Analyzing Huge Amounts of Data with Cloud-based IoT Analytics
Understanding the relationship between Internet of Things and Big Data
Understanding the Intel IoT Analytics structure
Setting up devices in Intel IoT Analytics
Setting up components in Intel IoT Analytics
Collecting sensor data with Intel IoT Analytics
Analyzing sensor data with Intel IoT Analytics
Triggering alerts with rules in Intel IoT Analytics
Test your knowledge
Summary
A. Exercise Answers
Chapter 1, Understanding and Setting up the Base IoT Hardware
Chapter 2, Working with Python on Intel Galileo Gen 2
Chapter 3, Interacting with Digital Outputs with Python
Chapter 4, Working with a RESTful API and Pulse Width Modulation
Chapter 5, Working with Digital Inputs, Polling and Interrupts
Chapter 6, Working with Analog Inputs and Local Storage
Chapter 7, Retrieving Data from the Real World with Sensors
Chapter 8, Displaying Information and Performing Actions
Chapter 9, Working with the Cloud
Chapter 10, Analyzing Huge Amounts of Data with Cloud-based IoT Analytics
Index
Internet of Things with Python
Internet of Things with Python
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2016
Production reference: 1170516
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-138-1
www.packtpub.com
Credits
Author
Gastón C. Hillar
Reviewer
Navin Bhaskar
Commissioning Editor
Kartikey Pandey
Acquisition Editor
Reshma Raman
Content Development Editor
Divij Kotian
Technical Editor
Nirant Carvalho
Copy Editor
Sneha Singh
Project Coordinator
Nikhil Nair
Proofreader
Safis Editing
Indexer
Hemangini Bari
Graphics
Gastón C. Hillar
Jason Monteiro
Production Coordinator
Shantanu N. Zagade
Cover Work
Shantanu N. Zagade
About the Author
Gastón C. Hillar is Italian and has been working with computers since he was eight. He began programming with the legendary Texas TI-99/4A and Commodore 64 home computers in the early 80s. He has a bachelor's degree in computer science, in which he graduated with honors, and an MBA, in which he graduated with an outstanding thesis. At present, Gastón is an independent IT consultant and freelance author who is always looking for new adventures around the world.
He has been a senior contributing editor at Dr. Dobb's and has written more than a hundred articles on software development topics. Gaston was also a Microsoft MVP in technical computing. He has received the prestigious Intel® Black Belt Software Developer award seven times.
He is a guest blogger at Intel® Software Network (http://software.intel.com). You can reach him at
His blog is http://csharpmulticore.blogspot.com.
He lives with his wife, Vanesa, and his two sons, Kevin and Brandon.
Acknowledgments
At the time of writing this book, I was fortunate to work with an excellent team at Packt Publishing Ltd, whose contributions vastly improved the presentation of this book. Reshma Raman allowed me to provide her with ideas to develop this book and I jumped into the exciting project of teaching how to combine electronic components, sensors, actuators, the Intel Galileo Gen 2 board, and Python to create exciting Internet of Things projects. Divij Kotian helped me realize my vision for this book and provided many sensible suggestions regarding the text, the format, and the flow. The reader will notice his great work. It was great working with Divij in another book. I would like to thank my technical reviewers and proofreaders for their thorough reviews and insightful comments. I was able to incorporate some of the knowledge and wisdom they have gained in their many years in the software development industry. This book was possible because they gave valuable feedback.
Special thanks go to my father, José C. Hillar, who introduced me to electronics before I started speaking. I grew up among transistors, resistors, and soldering irons. His clear vision of the evolution of electronic components, microcontrollers, and microprocessors made it possible for me to learn everything that was necessary to build Internet of Things projects. He worked with me while testing all the sample projects included in the book.
The interaction with a huge number of experts at Intel Developer Zone made it possible for me to become extremely familiar with the Intel Galileo and Intel Edison platforms, and start running Python code on them. My visits to Intel Developer Forum 2013, 2014 and 2015 made me understand all the things that developers must know in order to successfully create modern IoT projects. Special thanks go to Kathy Farrel and Aaron Tersteeg. Many conversations with them in San Francisco, California, kicked off my idea of writing this book.
The entire process of writing a book requires a huge number of lonely hours. I wouldn't have been able to write an entire book without dedicating some time to playing soccer with my sons, Kevin and Brandon, and my nephew, Nicolas. Of course, I never won a match. However, I did score a few goals.
About the Reviewer
Navin Bhaskar has over 4 years of experience in embedded systems, having written code ranging from device drivers to firmware for smart cards. He won the Distinctive Excellence award in the mbed design challenge for his Reconfigurable Computing for Embedded System project and the third prize for his EvoMouse in the OpenWorld contest. You can find his blog at https://navinbhaskar.wordpress.com/, where you can find tutorials on IoT and related topics.
www.PacktPub.com
eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
eBooks, discount offers, and morehttps://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
To my sons, Kevin and Brandon, and my wife, Vanesa
Preface
Internet of Things, also known as IoT, is changing the way we live and represents one of the biggest challenges in the IT industry. Developers are creating low-cost devices that collect huge amounts of data, interact with each other, and take advantage of cloud services and cloud-based storage. Makers all over the world are working on fascinating projects that transform everyday objects into smart devices with sensors and actuators.
A coffee cup is not a simple object anymore—it can send a message to your smartwatch indicating that the liquid inside has the right temperature so that you can drink it without worrying about checking whether it is too hot. In case you move the coffee cup before you receive the message, your wearable vibrates to indicate that you don't have to drink it yet.
You can check the coffee level of the coffee dispenser in your smartphone, and you won't have to worry about ordering more coffee: the coffee dispenser will automatically place an online order to request coffee when the coffee level is not enough to cover the rest of the day. You just need to approve the online order that the coffee dispenser suggests from your smartwatch. Based on certain statistical algorithms, the coffee dispenser will know the appropriate time to make the order.
What happens when more usual visitors arrive at the office? Their smartwatches or smartphones will communicate with the coffee dispensers and they will place orders in case the probable consumption of decaffeinated coffee increases too much. We have smart coffee cups, smart coffee dispensers, smartwatches, smartphones, and wearables. All of them take advantage of the cloud to create a smart ecosystem capable of providing us with all the different types of coffees we need for our day.
The Intel Galileo Gen 2 board is an extremely powerful and versatile minicomputer board for IoT projects. We can boot a Linux version and easily execute Python scripts that can interact with the different components included on the board. This book will teach you to develop IoT prototypes, from selecting the hardware to all the necessary stacks with Python 2.7.3, its libraries, and tools. In case you need a smaller board or an alternative, all the examples included in the book are compatible with Intel Edison boards, and therefore, you can switch to this board in case you need to.
Python is one of the most popular programming languages. It is open source, multiplatform, and you can use it to develop any kind of application, from websites to extremely complex scientific computing applications. There is always a Python package that makes things easier for us in order to avoid reinventing the wheel and solve problems faster. Python is an ideal choice for developing a complete IoT stack. This book covers all the things you need to know to transform everyday objects into IoT projects.
This book will allow you to prototype and develop IoT solutions from scratch with Python as the programming language. You will leverage your existing Python knowledge to capture data from the real world, interact with physical objects, develop APIs, and use different IoT protocols. You will use specific libraries to easily work with low-level hardware, sensors, actuators, buses, and displays. You will learn how to take advantage of all the Python packages with the Intel Galileo Gen 2 board. You will be ready to become a maker and to be a part of the exciting IoT world.
What this book covers
Chapter 1, Understanding and Setting up the Base IoT Hardware, start us off on our journey towards Internet of Things (IoT) with Python and the Intel Galileo Gen 2 board. We will learn the different features offered by this board and visualize its different components. We will understand the meaning of the different pins, LEDs, and connectors. We will learn to check the board's firmware version and to update if necessary.
Chapter 2, Working with Python on Intel Galileo Gen 2, leads us through many procedures that make it possible to work with Python as the main programming language to create IoT projects with our Intel Galileo Gen 2 board. We will write a Linux Yocto image to a microSD card, configure the board to make it boot this image, update many libraries to use their latest versions, and launch the Python interpreter.
Chapter 3, Interacting with Digital Outputs with Python, teaches us how to work with two different libraries to control digital outputs in Python: mraa and wiring-x86. We will connect LEDs and resistors to a breadboard and write code to turn on between 0 to 9 LEDs. Then, we will improve our Python code to take advantage of Python's object-oriented features, and we will prepare the code to make it easy to build an API that will allow us to print numbers with LEDs with a REST API.
Chapter 4, Working with a RESTful API and Pulse Width Modulation, has us working with Tornado Web Server, Python, the HTTPie command-line HTTP client, and the mraa and wiring-x86 libraries. We will generate many versions of RESTful APIs that will allow us to interact with the board in computers and devices connected to the LAN. We will be able to compose and send HTTP requests that print numbers in LEDs, change the brightness levels for three LEDs, and generate millions of colors with an RGB LED.
Chapter 5, Working with Digital Inputs, Polling and Interrupts, explains the difference between reading pushbutton statuses with polling and working with interrupts and interrupt handlers. We will write code that will allow the user to perform the same actions with either pushbuttons in the breadboard or HTTP requests. We will combine code that reacts to changes in the statuses of the pushbuttons with a RESTful API built with Tornado Web Server. We will create classes to encapsulate pushbuttons and the necessary configurations with the mraa and wiring-x86 libraries.
Chapter 6, Working with Analog Inputs and Local Storage, explains how to work with analog inputs to measure voltage values. We will measure voltages with an analog pin and both the mraa and the wiring-x86 libraries. We will be able to transform a variable resistor into a voltage source and make it possible to measure the darkness level with an analog input, a photoresistor, and a voltage divider. We will fire actions when the environment light changes, and we will work with both analog inputs and outputs. We will register events by taking advantage of the logging features included in the Python standard library and the USB 2.0 connector included in the Intel Galileo Gen 2 board.
Chapter 7, Retrieving Data From the Real World with Sensors, has us working with a variety of sensors to retrieve data from the real world. We will take advantage of the modules and classes included in the upm library that will make it easy for us to start working with analog and digital sensors. We will learn the importance of considering units of measurement because sensors always provide values measured in a specific unit, which we must consider. We will measure the magnitude and direction of proper acceleration or g-force, ambient temperature, and humidity.
Chapter 8, Displaying Information and Performing Actions, teaches us about different displays the we can connect to our board through the I²C bus. We will work with an LCD display with an RGB backlight, and we will then replace it with an OLED dot matrix. We will write code that takes advantage of the modules and classes included in the upm library to work with LCD and OLED displays and show text on them. We will also write code that interacts with an analog servo. We will control the shaft to allow us to create a gauge chart to display the temperature value retrieved with a sensor. Our Python code will make things move.
Chapter 9, Working with the Cloud, teaches you how to combine many cloud-based services that will allow us to easily publish data collected from sensors and visualize it in a web-based dashboard. We will work with the MQTT protocol and its publish/subscribe model to process commands in our board and indicate when the commands are successfully processed through messages. First, we will work with the PubNub cloud that works with the MQTT protocol under the hood. Then, we will develop the same example with Mosquitto and Eclipse Paho. We will be able to write applications that can establish bidirectional communications with our IoT devices.
Chapter 10, Analyzing Huge Amounts of Data with Cloud-based IoT Analytics, explains the close relationship between IoT and Big Data. We will work with Intel IoT Analytics, a cloud-based service that allows us to organize huge amounts of data collected by multiple IoT devices and their sensors. We will use the requests package to write a few lines of Python code to interact with the Intel IoT Analytics REST API. We will learn about the different options that Intel IoT Analytics offers us to analyze huge amounts of data, and we will define rules to trigger alerts.
What you need for this book
In order to work with the different tools required to connect to the Intel Galileo Gen 2 board and launch the Python samples, you will need any computer with an Intel Core i3 or higher CPU and at least 4 GB of RAM. You can work with any of the following operating systems:
Windows 7 or higher (Windows 8, Windows 8.1, or Windows 10)
Mac OS X Mountain Lion or higher
Any Linux version capable of running Python 2.7.x
Any modern browser with JavaScript support.
You will also need an Intel Galileo Gen 2 board and a breadboard with 830 tie points (holes for connections) and 2 power lanes.
In addition, you will need different electronic components and breakout boards to build the examples included in many chapters.
Who this book is for
This book is ideal for Python programmers who want to explore the tools available in the Python ecosystem in order to build their own IoT web stack and IoT-related projects. People from creative and designing backgrounds will also find this book equally useful.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: By default, the pip package management system that makes it easy to install and manage software packages written in Python isn't installed.
A block of code is set as follows:
if __name__ == __main__
:
print (Mraa library version: {0}
.format(mraa.getVersion()))
print (Mraa detected platform name: {0}
.format(mraa.getPlatformName()))
number_in_leds = NumberInLeds()
# Count from 0 to 9
for i in range(0, 10):
number_in_leds.print_number(i)
time.sleep(3)
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
class NumberInLeds:
def __init__(self):
self.leds = []
for i in range(9, 0, -1): led = Led(i, 10 - i)
self.leds.append(led)
def print_number(self, number):
print(==== Turning on {0} LEDs ====
.format(number))
for j in range(0, number):
self.leds[j].turn_on()
for k in range(number, 9):
self.leds[k].turn_off()
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: The next time you have to upload a file to the board, you don't need to set up a new site in the Site Manager dialog box in order to establish an SFTP connection.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Internet-of-Things-with-Python. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/InternetofThingswithPython_ColorImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.
Chapter 1. Understanding and Setting up the Base IoT Hardware
In this chapter, we will start our journey towards Internet of Things (IoT) with Python and the Intel Galileo Gen 2 board. Python is one of the most popular and versatile programming languages. You can use Python to create multiplatform desktops and Web, mobile, and scientific applications. You can work with huge amounts of data and develop the complex algorithms that are popular in Big Data scenarios with Python. There are thousands of Python packages, which allow you to extend Python capabilities to any kind of domain you can imagine.
We can leverage our existing knowledge of Python and all of its packages to code the different pieces of our IoT ecosystem. We can use the object-oriented features, which we love from Python. in code that interacts with the Intel Galileo Gen 2 board and the electronic components connected to it. We can use the different packages that make it possible for us to easily run a Web server and provide a RESTful API. We can use all the packages that we already know to interact with databases, Web services, and different APIs. Python makes it easy for us to jump into the IoT world. We don't need to learn another programming language, we can use