1
votes

I run a simple mqtt publisher c code that subscribe "Hello World".

mqtt subscriber1:

mosquitto_sub -h xx.xx.xx.xx -t "mq_test" 

Consecutively i run the same mqtt publisher code in another location and subscribe with different topic to same host.

mqtt subscriber2:

mosquitto_sub -h xx.xx.xx.xx -t "mq_t"

When i starts the second publisher program, first mqtt subscription stops. Why this issue occurs, i think it is possible to subscribe to multiple topics.

mqtt publisher c code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <MQTTClient.h>
#define ADDRESS     "tcp://xx.xx.xx.xx:abcd"
#define CLIENTID    "ExampleClientPub"
#define TOPIC       "mq_test" //"mq_t"
#define PAYLOAD     "Hello World!"
#define QOS         1
#define TIMEOUT     10000L
int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc = 0;
    MQTTClient_create(&client, ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 5;
    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);
    }
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    while(1){
        rc = 0;
         pubmsg.payload = PAYLOAD;
        pubmsg.payloadlen = strlen(PAYLOAD);
        pubmsg.qos = QOS;
        pubmsg.retained = 0;
        MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
        printf("Waiting for up to %d seconds for publication of %s\n"
            "on topic %s for client with ClientID: %s\n",
            (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
         rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
         printf("Message with delivery token %d[%d] delivered\n", token,rc);
    }
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}
3
Can you please add the subscription code snippet?Vardit

3 Answers

1
votes

You are using same code for multiple mqtt publisher only by changing topic and client id in both publisher remain same.please try out the scenario by giving different client id for the publishers.

0
votes
#define CLIENTID    "ExampleClientPub"

Each application/program that connects to an MQTT Broker needs their own unique clientId.
i.e. "MyClnt001", "MyClnt002", "MyClnt003", etc.

0
votes

You can subscribe to multiple topics from mosquitto_sub client with multiple -t options as below:

mosquitto_sub -t topic1 -t topic2 -t topic3

Programmatically, you can achieve this by connecting once (with one clienId) and subscribing multiple times in a loop with different topics if your client library supports subscribing on the existing connection.