Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

Incorporating MQTT Retained Messages in C and Python Projects for Intermediate Programmers

August 28, 2023

Incorporating MQTT Retained Messages in C and Python Projects for Intermediate Programmers

In this post, we will explore how to incorporate MQTT retained messages in C and Python projects. Retained messages are a powerful feature in MQTT that allow subscribers to receive the last published message on a specific topic immediately after they subscribe, even if no new message has been published since the subscription. This can be particularly useful in scenarios where a subscriber needs to know the current state of a particular topic as soon as it connects to the broker.

Understanding MQTT Retained Messages

Before we dive into the code examples, let’s briefly revisit the concept of retained messages in MQTT. When a publisher sends a message with the retained flag set to true, the broker not only delivers the message to any subscribers who are currently listening on that topic, but also retains the message for future subscribers. Any new subscriber who subscribes to that topic will immediately receive the retained message, if one exists.

MQTT Client Libraries

For our examples, we will be using the Eclipse Paho MQTT client libraries for both C and Python. These libraries provide a simple and powerful interface for interacting with MQTT brokers.

C Example

 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
#include <stdio.h>
#include <string.h>
#include "MQTTClient.h"

#define CLIENTID    "ExampleClient"
#define TOPIC       "exampleTopic"
#define QOS         1
#define RETAINED    1

int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;

    MQTTClient_create(&client, "tcp://localhost:1883", CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    pubmsg.payload = "Hello, MQTT!";
    pubmsg.payloadlen = (int)strlen(pubmsg.payload);
    pubmsg.qos = QOS;
    pubmsg.retained = RETAINED;

    MQTTClient_connect(client, &conn_opts);

    MQTTClient_publishMessage(client, TOPIC, &pubmsg, NULL);

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

In this C example, we are using the Paho MQTT C client library to publish a message with the retained flag set to true on a topic named “exampleTopic”.

Python Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import paho.mqtt.client as mqtt

client = mqtt.Client("ExampleClient")

def on_connect(client, userdata, flags, rc):
    client.publish("exampleTopic", "Hello, MQTT!", qos=1, retained=True)
    client.disconnect()

client.on_connect = on_connect

client.connect("localhost", 1883, 60)
client.loop_forever()

In this Python example, we are using the Paho MQTT Python client library to publish a message with the retained flag set to true on the same “exampleTopic” as in the C example.

Subscribing to Retained Messages

Now that we have published a message with the retained flag set, let’s create a subscriber to receive the retained message using both C and Python.

C Subscriber Example

 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 "MQTTClient.h"

#define CLIENTID    "ExampleClient"
#define TOPIC       "exampleTopic"
#define QOS         1

int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;

    MQTTClient_create(&client, "tcp://localhost:1883", CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    
    MQTTClient_message pubmsg = MQTTClient_message_initializer;

    MQTTClient_connect(client, &conn_opts);

    MQTTClient_subscribe(client, TOPIC, QOS);
    while(1) {
        MQTTClient_receive(client, TOPIC, &pubmsg);
        if (pubmsg.retained) {
            printf("Retained message: %s\n", pubmsg.payload);
            break;
        }
    }

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

In this C example, we are using the Paho MQTT C client library to subscribe to the “exampleTopic” and receive the retained message if it exists. Once the retained message is received, we print it to the console.

Python Subscriber Example

 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):
    client.subscribe("exampleTopic", qos=1)

def on_message(client, userdata, msg):
    if msg.retain:
        print("Retained message: {}".format(msg.payload))
        client.disconnect()

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 are using the Paho MQTT Python client library to subscribe to the “exampleTopic” and receive the retained message if it exists. Once the retained message is received, we print it to the console and disconnect from the broker.

Conclusion

Incorporating MQTT retained messages in C and Python projects can be a valuable capability to have, especially in scenarios where subscribers need immediate access to the current state of specific topics. By using the Eclipse Paho MQTT client libraries, intermediate programmers can effectively publish and subscribe to retained messages with ease.

I hope this post has been helpful in understanding how to incorporate MQTT retained messages in C and Python projects. Feel free to experiment with these examples and explore the possibilities of using retained messages in your own MQTT projects.

Happy coding!


➡️ Designing Efficient MQTT Payloads for C and Python Applications: Intermediate Tips


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


Go back to Posts.