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

The on_message() MQTT callback method

It's the on_message() handler at line (11) that is called whenever a new message for a subscribed topic is received by our program. The message is available through the msg parameter, which is an instance of MQTTMessage

At line (12), we access the payload property of msg and decode it into a string. We expect our data to be a JSON string (for example, { "level": 100 }), so we parse the string into a Python dictionary using json.loads() and assign the result to data. If the message payload is not valid JSON, we catch the exception and log an error:

def on_message(client, userdata, msg):                    # (11)
data = None
try:
data = json.loads(msg.payload.decode("UTF-8")) # (12)
except json.JSONDecodeError as e:
logger.error("JSON Decode Error: "
+ msg.payload.decode("UTF-8")...