Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

Working with MQTT Topics and Subscriptions in C and Python: Intermediate Development Techniques

August 20, 2023

Working with MQTT Topics and Subscriptions in C and Python: Intermediate Development Techniques

In this blog post, we’ll delve into the intricate world of MQTT (Message Queuing Telemetry Transport) topics and subscriptions, exploring advanced development techniques in C and Python. By the end of this post, you’ll have gained a comprehensive understanding of how to work with these features, enabling you to create efficient and powerful MQTT-based applications.

Understanding MQTT Topics and Subscriptions

Before we delve into the implementation details, let’s briefly recap what MQTT topics and subscriptions are:

Implementing MQTT Topics and Subscriptions in C

Using the Eclipse Paho MQTT C Client Library

We can use the Eclipse Paho MQTT C client library to work with MQTT in C. Here’s an example of how to subscribe to an MQTT topic using the 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <MQTTClient.h>

#define ADDRESS "tcp://mqtt.eclipse.org:1883"
#define CLIENTID "ExampleClientSub"
#define TOPIC "sensors/temperature"
#define QOS 1
#define TIMEOUT 10000L

void delivered(void *context, MQTTClient_deliveryToken dt) {
    printf("Message with token value %d delivery confirmed\n", dt);
}

int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message) {
    printf("Message arrived\n");
    printf("  topic: %s\n", topicName);
    printf("  message: %.*s\n", message->payloadlen, message->payload);
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return 1;
}

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;

    MQTTClient_setCallbacks(client, NULL, NULL, msgarrvd, delivered);

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

    printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n", TOPIC, CLIENTID, QOS);
    MQTTClient_subscribe(client, TOPIC, QOS);

    while (1) {}

    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}

In this example, we create an MQTT client and set up a callback function msgarrvd to handle incoming messages. We then subscribe to the sensors/temperature topic and enter a loop to keep the program running and processing incoming messages.

Implementing MQTT Topics and Subscriptions in Python

Using the paho-mqtt Library

In Python, we can use the paho-mqtt library to work with MQTT. Here’s an example of how to subscribe to an MQTT topic using the library:

 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("sensors/temperature")

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

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

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

client.loop_forever()

In this Python example, we create an MQTT client and define callback functions on_connect and on_message to handle the connection and incoming messages, respectively. We then connect to the MQTT broker, subscribe to the sensors/temperature topic, and enter a loop to keep the program running and processing incoming messages.

Conclusion

In this blog post, we’ve explored how to work with MQTT topics and subscriptions in C and Python, using the Eclipse Paho MQTT C client library and the paho-mqtt library, respectively. By understanding these advanced development techniques, you’ll be well-equipped to create robust and scalable MQTT-based applications in both languages. Experiment with the provided examples and start incorporating MQTT into your projects to leverage the power of asynchronous messaging!

Happy coding!


➡️ Using MQTT with SSL/TLS for Secure Communication in C and Python Applications


⬅️ Handling MQTT Connection Management in C and Python Applications: Best Practices for Intermediate Programmers


Go back to Posts.