Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

Getting Started with MQTT: A Guide for Intermediate C and Python Programmers

July 11, 2023

Getting Started with MQTT: A Guide for Intermediate C and Python Programmers

As an intermediate C and Python programmer, you may be familiar with the basics of network programming and messaging protocols. However, diving into MQTT (Message Queuing Telemetry Transport) can open up a world of possibilities for efficient and reliable communication between devices and applications. In this guide, we’ll explore the fundamentals of MQTT, how to use it in C and Python, and provide detailed examples to help you get started.

Understanding MQTT

MQTT is a lightweight and scalable messaging protocol designed for efficient communication between devices in a publish-subscribe model. It is ideal for constrained environments such as IoT devices, where bandwidth and power are limited. MQTT operates on top of TCP/IP, making it suitable for both local and wide-area networks.

The key concepts of MQTT include:

Using MQTT in C

To start working with MQTT in C, you can use the Eclipse Paho MQTT C client library, which provides a comprehensive set of APIs for publishing and subscribing to MQTT topics. Here’s a basic example of how to publish a message using the Paho MQTT C client:

 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
35
36
37
38
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"

#define MQTT_BROKER_ADDRESS "tcp://localhost:1883"
#define MQTT_CLIENT_ID "ExampleClient"
#define MQTT_TOPIC "example/topic"

int main(int argc, char* argv[]) {
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    char* payload = "Hello, MQTT!";
    int rc;

    MQTTClient_create(&client, MQTT_BROKER_ADDRESS, MQTT_CLIENT_ID, 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(-1);
    }

    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    pubmsg.payload = payload;
    pubmsg.payloadlen = strlen(payload);
    pubmsg.qos = 1;
    pubmsg.retained = 0;

    MQTTClient_deliveryToken token;
    MQTTClient_publishMessage(client, MQTT_TOPIC, &pubmsg, &token);

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

    return 0;
}

In this example, we create an MQTT client, connect to a broker, and publish a message to the specified topic. You can also subscribe to topics and handle incoming messages using the Paho MQTT C client library.

Using MQTT in Python

For Python programmers, the Eclipse Paho MQTT Python client library offers a similar set of functionalities for working with MQTT. Here’s a simple example of how to subscribe to a topic and receive messages using the Paho MQTT Python client:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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("localhost", 1883, 60)

client.loop_forever()

In this Python example, we create an MQTT client, connect to a broker, subscribe to a topic, and handle incoming messages using callback functions.

Conclusion

MQTT is a versatile and efficient messaging protocol that can greatly enhance the communication capabilities of your C and Python applications. By using the Eclipse Paho MQTT client libraries and understanding the fundamental concepts of MQTT, you can easily integrate MQTT into your projects and build robust, scalable communication systems.

In this guide, we’ve only scratched the surface of MQTT. As an intermediate C and Python programmer, I encourage you to further explore the features and advanced use cases of MQTT to leverage its full potential in your projects. Happy coding!


In this blog post, we covered the fundamentals of MQTT, provided examples in both C and Python, and explained how to use the Eclipse Paho MQTT client libraries. I hope this guide helps you get started with MQTT and enables you to incorporate it into your programming projects. If you have any questions or suggestions, feel free to leave a comment below. Thank you for reading!


➡️ Embracing functional programming concepts for clean code in Python


⬅️ Utilizing clean code principles for efficient memory management in C


Go back to Posts.