Best Practices of Internet of Things Programming with Python

14009-internet_of_things_with_python.jpg

Oftentimes, prototypes or real-life Internet of Things (IoT) systems need to be developed quickly and efficiently. When this happens, two tasks immediately come to life: programming the IoT devices and organizing a backend that interacts with these devices.

In both tasks, you can use Python as the development language. Or, you can use a completely functional and practical version of MicroPython to work on devices with little computing resources, and accordingly, at a very low cost. Let’s take a look at how you can use Python to program IoT devices and create a backend for them to work.

IoT with Python became an effective tool for prototyping, development, and the operation of various devices and systems of the Internet of Things. Python can be effectively used for programming IoT devices as well as developing the corresponding backend. The speed of development, the low threshold for learning Python, and the large set of Python libraries make this programming language indispensable for IoT.

Table of contents:

  1. Why the Internet of Things?
  2. Why use Python in IoT.
  3. The best solutions for IoT in Python.
  4. IoT Backend with Python.
  5. Conclusion.

Why the Internet of Things?

We can date the term "Internet of Things" back to 1999, coined by Kevin Ashton. Ever since its importance and scale have exploded, in fact, one of the main indicators is its market size of $201 billion in 2022, with a steady increase year over year. Based on this forecast, the global IoT market is expected to reach $650 billion by 2026 with a CAGR of 16.7%.

Back in the day, IoT was explained with examples like this one: “You can use your phone to turn a light bulb on and off in your room.”

Nowadays, hardly anyone would be surprised by a smart electricity meter that transmits readings of electricity consumption, uploads that info to the cloud, and generates monthly bills sent directly to your email.

Across industries, IoT is being increasingly used to streamline processes and make them more efficient. For example, manufacturing production lines and agriculture are great examples of different industries taking advantage of the many benefits of IoT. In the specific case of agriculture, IoT helps coordinate harvesters with trucks that have elevators to efficiently handle grains.

Why use Python in IoT

For many developers, Python is the language of choice in the market. It’s easy to learn, has clean syntax, and it is supported by a large community online. In IoT, Python is a great choice for the backend side of development as well as the software development of devices. In addition, Python is available to run on Linux devices and you can use MicroPython for microcontrollers.

In this article, it is said that “using this coding language [helps] you reduce the volume of data that you have to deal with and that is accessible in the cloud. Regardless of whether you are creating your IoT project from scratch or interacting with sensors, actuators, and accessories, Python recognizes your requirements.”

Some of the many advantages of working with Python for IoT devices are the speed at which you can develop code and a large number of libraries for all kinds of platforms. Python is a great ally to develop device prototypes. Even if you rewrite some of your code during production to C, C++, or Java to improve performance, in general, the system will function perfectly in Python.

The logical design of using Python in IoT is easy enough to develop from the standpoint of an IoT system architecture. By using modern IoT frameworks and protocols for transferring data from devices, you can effectively build high-performing IoT systems. This form of architecture scales well for a large number of connected IoT devices and works just as well with large amounts of data.

The best solutions for IoT in Python

Python on Raspberry Pi

The first thing that comes to mind about running Python on an IoT device is grabbing your beloved Raspberry Pi from the table. Python is pre-installed in the operating system and the only thing left is for you to write your own script.

In this case, you can control the I/O ports on the Raspberry Pi expansion bar. Fortunately, the board supports wireless communication (Bluetooth and WiFi), Ethernet, and you can also connect a monitor to the HDMI outputs, a specialized 3.2" 320x240 TFT LCD, or a low energy consumption E-Ink 2.13" 250x122 display for Raspberry Pi.

The controllers, available in a wide range of computing power and budgets, can be chosen for your IoT system - from the fast Raspberry Pi 4 Model B 8GB to the smallest Raspberry Pi Zero, all supporting Python. If necessary, you can install the previous version of Python 2.7 for past compatibility.

To control the I/O ports, you can easily write a couple of lines in Python using the GPIO Zero library:

from gpiozero import Button
from time import sleep

button = Button(2)

while True:
    if button.is_pressed:
        print("Button Press")
    else:
        print("Button Release")
    sleep(1)
Code language: JavaScript (javascript)

This example shows how easy it is to receive and process signals by pressing the button on the second pin at the moment of pressing and at the moment of releasing.
 
The advantages of using this approach are the availability of a wide range of development tools, libraries, and communications for the most complex devices based on Raspberry Pi, including video processing from cameras.

Python on PyBoard

The next great solution for Python in IoT devices is the PyBoard with an STM32F405RG microcontroller.

The PyBoard is a compact and powerful electronics development board that runs MicroPython. It connects to your PC via USB, giving you a USB flash drive to save your Python scripts and a serial Python prompt (a REPL) for instant programming. This works with Windows, Mac, and Linux.

PyBoard runs MicroPython, a lightweight implementation of the standard CPython interpreter. As written on their site: “MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimized to run on microcontrollers and in constrained environments. The MicroPython pyboard is a compact electronic circuit board that runs MicroPython on the bare metal, giving you a low-level Python operating system that can be used to control all kinds of electronic projects. MicroPython is packed full of advanced features such as an interactive prompt, arbitrary precision integers, closures, list comprehension, generators, exception handling, and more. Yet it is compact enough to fit and run within just 256k of code space and 16k of RAM."

MicroPython is a complete re-write of the Python (version 3.4) programming language so that it fits and runs on a microcontroller. It includes many optimizations for efficiency and it uses very little RAM.

Internet of Things

MicroPython runs bare-metal on the PyBoard, essentially giving you a Python operating system. The built-in pyb module contains functions and classes to control the peripherals available on the board, such as UART, I2C, SPI, ADC, and DAC.

The dimensions of the board are impressive, taking up about two quarters, 33mm x 43mm, and weighing just 6 grams.

ESP8266, ESP32 with Micropython

Go ahead, if you need to create an IoT device with low power consumption, great capabilities, and integration with wireless WiFi networks, you can run Python on ESP8266, ESP32. More precisely, MicroPython.

After installing Python on your computer, you can enter the pip install esptool from the command line. The MicroPython installation process is quite simple: download the firmware from the website and install it using esptool, not forgetting to format the board before installing it.

There are already quite a few IDEs for developing with Micropython. The entire development process is carried out on a working computer, then it is compiled and stored in the memory of an ESP8266 or ESP32 microcontroller. See how simple this code might look like:

from machine import Pin
import time

led_pin = Pin(2,Pin.OUT)

while True:
    led_pin.on()
    time.sleep(1)
    led_pin.off()
    time.sleep(1)
Code language: JavaScript (javascript)

MicroPython will impose a lot of restrictions compared to regular Python but, in general, you can easily write the necessary functionality on the client-side and run it efficiently on ESP microcontrollers. This solution is more cost-effective than purchasing PyBoard.

IoT Backend with Python

MQTT protocol with Python

The most popular connection method for IoT devices is MQTT, a protocol that is effectively implemented with Python.

The MQTT protocol is a machine-to-machine (M2M)/Internet of Things connectivity protocol that is designed as an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium.

The Eclipse Paho MQTT Python client library implements versions 5.0, 3.1.1, and 3.1 of the MQTT protocol.

The Poho library code provides a client class that enables applications to connect to an MQTT broker to publish messages, subscribe to topics, and receive published messages. It also provides some helper functions to make the publishing of one-off messages to MQTT servers straightforward.

We find it interesting that the library supports Python 2.7.9+ or 3.5+. The image integration with older 2.7 versions of Python is easier.

IoT backend on Flask in Python

For a quick, and hassle-free tool to write the backend for your IoT systems and easily set up server-side input/output information, the Flask microframework is here to rescue you and is packed with lots of functionalities.

To get started, decide on the requests you need to serve from your IoT devices, set up the Flask microframework, and write a couple of lines of code. The GET method will now return information upon request from the client’s side.

In many cases, you are best off targeting the RESTful protocol when working with your IoT devices. This simplifies the exchange between the system components and allows you to expand the information exchange system in the future.

Let's go further. Let's say the following task has arisen: display information from IoT devices on a web page. The Flask microframework will rescue you again with its built-in template mechanism where you can build the needed web page with the data display, including graphics.

The disadvantage of using this approach is the potential lack of initiating the transfer of data from the server to the device. That is, the IoT must independently and periodically pull from the server. Rest easy, as there are solutions to address this risk. You can use web sockets or a Python library for Pushsafer. With PushSafer, you can easily and safely send and receive push notifications in real-time to your iOS, Android, and Windows devices (mobile and desktop), as well as browsers like Chrome, Firefox, Opera, etc.

Microsoft Azure IoT backend in Python

Microsoft has released a new open-source IoT extension that extends the capabilities of Azure CLI 2.0. 

Azure CLI 2.0 includes commands to interact with the Azure Resource Manager and management endpoints.

For example, you can use Azure CLI 2.0 to create an Azure VM or IoT Hub. The CLI Extension allows an Azure service to complement Azure CLI by giving users access to additional service-specific capabilities.

The IoT Extension gives developers command-line access to the capabilities of the IoT Hub, IoT Edge, and IoT Hub Device Provisioning Service.

Azure CLI 2.0 enables immediate management of Azure IoT Hub resources, device provisioning service instances, and associated hubs. The new IoT extension enriches Azure CLI 2.0 with features like device management and all IoT Edge capabilities:

  • Azure CLI 2.0 IOT capabilities - control plane
  • Manage loT hub instances, consumer—groups, and jobs
  • Manage device provisioning service instances, access-policies, Linked—hub, and certificates
  • New features for extensions — data plane
  • Manage device and edge module identities as well as their respective twin definitions
  • Query loT Hub for info such as device and module twins, jobs, and messaging routing
  • Invoke device and module methods
  • Generate SAS tokens and grab connection strings
  • Cloud-to-device and device-to-cloud messaging
  • Device file upload
  • Device simulation for testing

Here you can read more details of how the Azure IoT backend works with Python.

Python packages for IoT are widely available and are usually free. This includes both development tools for IoT devices and tools for back-end development, analysis, and data processing. For example, Eclipse Paho™ MQTT Python Client - works great with the MQTT protocol and is widely used to build IoT devices. Similarly, Sockets and Mraa allow you to work with TCP/IP protocols and data input/output with GPIO.

If you are seriously interested in learning more about the Internet of Things with Python, we recommend that you take some training courses such as "Internet of Things with Python Programming". This course allows you to get comfortable with the basics of Hardware and Software. You will also be introduced to advanced concepts such as functional programming, object orientation, and exception handling.

Conclusion

You may be slightly surprised, but it isn’t Python that makes working with IoT devices and the backend so convenient. There are several factors that come into play, working together to improve the usability of Python for IoT:

  • A low threshold to enter basic constructions of the programming language.
  • A huge number of libraries for a variety of tasks
  • An element base to run Python on the client’s side
  • Ability to write a backend in various Python frameworks
  • Easy backend integration with the client-side of IoT, as both are written in Python
  • Low system requirements, especially for Micropython
  • Cloud support
  • A large number of trained specialists.

Python will not be able to do everything for you, but it will significantly help you create the first prototype, and in the next versions of your IoT system, it will also perform assigned functions in conjunction with other programming languages and libraries.

Svitla Systems specialists have extensive experience in creating backends for IoT systems and configuring IoT client devices, not only in Python but also in other programming languages. Contact us to create your new projects from scratch where you’ll find that our system analysts will help you from the early stages of the project, our developers will write the program code, and our testers will put all systems in the complex to the test. 

Internet of Things projects will make the real world a better place and people’s lives will be better for it. Our drive is to help you make all your IoT projects successful. Contact our IoT experts for more information.