0
votes

I have been trying to develop a C code using mosquitto lib to publish message on a mosquitto broker over TLS. I configured the TLS on mosquitto side and it worked fine. I was able to send and receive messages using mosquitto_pub and mosquitto_sub.

However, when I tried to publish a message using my C code, it does not work. Apparently, the code connects fine and sends the message, there is no error but the subscriber does not read anything.

Below is the publisher code I am using:

ReportSender::ReportSender()
{
    mosquitto_lib_init();

    mosquitoStruct = mosquitto_new (NULL, true, NULL);

    mosquitto_tls_opts_set(mosquitoStruct, 1, NULL, NULL);

    mosquitto_tls_set(mosquitoStruct, "~/temp/keys/secondAttempt/server.crt", NULL, NULL, NULL, NULL);

    mosquitto_tls_insecure_set(mosquitoStruct, false);

    mosquitto_connect_callback_set(mosquitoStruct, connect_cb);
    mosquitto_publish_callback_set(mosquitoStruct, publish_cb);
    mosquitto_log_callback_set(mosquitoStruct, log_cb);

    mosquitto_connect (mosquitoStruct, MQTT_BROKER, MQTT_PORT, 0);

    const char *reportRef = "Hello Word!";

    // Publish the message to the topic
    mosquitto_publish (mosquitoStruct, NULL, MQTT_TOPIC,
              strlen(reportRef), reportRef, 0, false);

    sleep (20);
}

And the subscriber is:

mosquitto_sub -h 192.168.56.101 -p 8883 -t "#" -v --cafile server.crt

What is wrong?

Thanks, Mauro

1
Are you sure that mosquitto_connect is a blocking call?. If not you will call publish before the connection has completed. You may have to move the mosquitto_publish call to the connect_cb callback - hardillb

1 Answers

1
votes

You should look at the loop*() set of functions, these are needed to process the background network traffic. publish() is not a blocking call.