Connecting to MQTT with Python's asyncio

Mar 25, 2024 ยท 2 min read

MQTT is a popular lightweight messaging protocol used in IoT and mobile applications. Python's asyncio module makes it easy to handle MQTT subscriptions and publications asynchronously without blocking the main thread.

Let's walk through a practical example of connecting to an MQTT broker with asyncio.

First we need an MQTT client library. We'll use Eclipse Paho MQTT _, a popular open source library. Install it with:

pip install paho-mqtt

Next we create an MQTT client instance, specify the broker URL, and set some options like the client ID:

import paho.mqtt.client as mqtt

client = mqtt.Client(client_id="my_client")
client.connect("test.mosquitto.org") 

To use MQTT with asyncio, we need an asyncio loop and to run the network IO in an executor thread:

import asyncio
from asyncio import SelectorEventLoop
from concurrent.futures import ThreadPoolExecutor

loop = SelectorEventLoop()
executor = ThreadPoolExecutor()

We can now connect and subscribe in an async coroutine:

async def main():
    await loop.run_in_executor(executor, client.connect, "test.mosquitto.org")  
    client.subscribe("my/test/topic")

The key thing is to use run_in_executor to run the MQTT calls in the thread pool instead of blocking the main thread.

To publish messages, we do the same:

async def publish():
    msg = "Hello MQTT"
    await loop.run_in_executor(executor, client.publish, "my/test/topic", msg)

And that's the basics of using MQTT with Python's handy asyncio functionality! Asyncio makes it simple to do non-blocking MQTT in Python.

Some key takeaways:

  • Use paho-mqtt client for MQTT in Python
  • Create a thread pool executor to run MQTT calls
  • Use run_in_executor to run MQTT non-blocking from coroutines
  • Subscribe, publish, connect etc can now be done asynchronously
  • Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: