0

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

Mauro Silva
  • 181
  • 1
  • 2
  • 9
  • 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 Apr 30 '18 at 08:15

1 Answers1

1

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

ralight
  • 11,033
  • 3
  • 49
  • 59
  • Just checking, what about connect? I assume that should be async as well (given the callback) – hardillb Apr 30 '18 at 14:05
  • Connect is blocking only in as far as establishing the network socket goes. A successful return from it means that the socket is established. It doesn't mean anything about the mqtt packet flow - you get that from the callback. – ralight May 01 '18 at 13:10
  • cool, so we need the loop functions (to handle the actual MQTT back and forth) and to move the `publish` call to the `on_connect` callback so it doesn't get called until the client is ready – hardillb May 01 '18 at 14:19
  • It's not necessary to move publish to on_connect, but it wouldn't hurt. It would mean it gets republished each time you reconnect of course. – ralight May 01 '18 at 15:18
  • Thanks a lot for all your help! It worked! The issue was that the connect function was not blocking! I made a quick change on the code to validate it and as soon as I have the final code, i publish here. Thanks again. – Mauro Silva May 02 '18 at 21:48