Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

Handling MQTT Message Queuing for C and Python Programmers

July 23, 2023

Handling MQTT Message Queuing for C and Python Programmers

Message Queuing Telemetry Transport (MQTT) is a lightweight and efficient messaging protocol designed for use in situations where low bandwidth and high latency are common. MQTT enables devices to communicate with each other using a minimal amount of code and resources, making it an ideal choice for Internet of Things (IoT) and other resource-constrained environments.

In this blog post, we will explore how to handle MQTT message queuing using C and Python, providing extensive examples and detailed explanations of the concepts involved.

Introduction to MQTT

MQTT operates on the publish-subscribe messaging pattern, where devices can publish messages to a central broker and subscribe to receive messages from the broker. This approach allows for efficient communication between devices without the need for direct, point-to-point connections.

The key components of an MQTT system include:

  1. Broker: A server that receives all messages from the publishing clients and routes them to the subscribing clients.

  2. Publisher: A client that sends messages to the broker.

  3. Subscriber: A client that receives messages from the broker.

MQTT in C

Using an MQTT Library

To handle MQTT message queuing in C, we can leverage an MQTT client library such as Eclipse Paho MQTT C. Here’s a simple example demonstrating how to publish and subscribe to MQTT messages using the Paho MQTT C library:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"

#define ADDRESS "tcp://mqtt.eclipse.org:1883"
#define CLIENTID "ExampleClientC"
#define TOPIC "example/topic"
#define QOS 1
#define TIMEOUT 10000L

int main() {
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc;

    MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;

    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) {
        printf("Failed to connect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }

    char message[100] = "Hello, MQTT!";
    MQTTClient_publish(client, TOPIC, strlen(message), message, QOS, 0, NULL);
    printf("Message published: %s\n", message);

    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);

    return EXIT_SUCCESS;
}

In this example, we initialize an MQTT client, connect to an MQTT broker, and publish a message to the specified topic.

For subscribing to messages, we can modify the code to include subscription logic using the MQTTClient_subscribe function.

Handcrafting MQTT Protocol

Alternatively, for educational purposes, we can delve into the inner workings of MQTT and handcraft our own MQTT client in C by directly sending MQTT packets over a network socket. This approach allows for a deeper understanding of the MQTT protocol and is a valuable learning experience for C programmers.

MQTT in Python

Using paho-mqtt Library

For Python programmers, the paho-mqtt library provides a convenient way to handle MQTT message queuing. Let’s look at an example of publishing and subscribing to MQTT messages using paho-mqtt:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("example/topic")

def on_message(client, userdata, msg):
    print("Received message: "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("mqtt.eclipse.org", 1883)

client.publish("example/topic", "Hello, MQTT!")

client.loop_forever()

In this Python example, we create an MQTT client, connect to an MQTT broker, publish a message to a topic, and subscribe to receive messages from the same topic.

Asyncio and paho-mqtt

Python programmers can also use the asyncio library in conjunction with paho-mqtt to handle MQTT message queuing in an asynchronous, event-driven manner. Here’s an example of using asyncio and paho-mqtt to handle MQTT communication asynchronously:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import asyncio
import paho.mqtt.client as mqtt

async def handle_mqtt():
    client = mqtt.Client()
    await loop.sock_connect(client, ("mqtt.eclipse.org", 1883))

    async def on_message(client, userdata, msg):
        print("Received message: "+str(msg.payload))

    client.on_message = on_message
    client.connect("mqtt.eclipse.org", 1883)
    client.subscribe("example/topic")

    while True:
        await loop.sock_accept(client)
        client.loop()

loop = asyncio.get_event_loop()
loop.run_until_complete(handle_mqtt())

In this example, we use the asyncio library to handle MQTT communication in an asynchronous manner, allowing for non-blocking handling of MQTT messages.

Conclusion

In this blog post, we’ve explored how to handle MQTT message queuing for C and Python programmers, providing extensive examples and detailed explanations of the concepts involved. By leveraging MQTT libraries and understanding the underlying MQTT protocol, developers can effectively integrate MQTT communication into their C and Python applications.

Whether using existing MQTT client libraries or handcrafting MQTT communication for educational purposes, C and Python programmers have the flexibility to work with MQTT and leverage its benefits in their projects.


➡️ Best practices for handling input and output in clean C and Python code


⬅️ Avoiding code smells and anti-patterns in C and Python programming


Go back to Posts.