#include <mosquitto.h>
#include <mqtt_protocol.h>
#include <thread>
#include <cstring>
#define SERVER_HOST "127.0.0.1"
#define SERVER_PORT 1883
/* Callback called when the client receives a message. */
static void on_message(struct mosquitto* mosq, void* obj, const struct mosquitto_message* msg, const mosquitto_property* props)
{
printf("%s called with topic %s\n", __FUNCTION__, msg->topic);
return;
}
int main(void)
{
struct mosquitto* mosq_;
char msg[] = "testmsg";
int qos = 0;
mosquitto_lib_init();
mosq_ = mosquitto_new("tx", false, NULL);
if (mosq_ == NULL)
return 1;
// Commenting this function call results in the `on_message` being called exactly once.
// With this line it is called 3 times (for each mosquitto_subscribe).
mosquitto_int_option(mosq_, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5);
mosquitto_message_v5_callback_set(mosq_, on_message);
mosquitto_connect(mosq_, SERVER_HOST, SERVER_PORT, 60);
mosquitto_loop_start(mosq_);
mosquitto_subscribe(mosq_, NULL, "#", qos);
mosquitto_subscribe(mosq_, NULL, "1/#", qos);
mosquitto_subscribe(mosq_, NULL, "1/2/#", qos);
mosquitto_publish_v5(mosq_, NULL, "1/2/3", strlen(msg), static_cast<void*>(msg), qos, false, NULL);
std::this_thread::sleep_for(std::chrono::seconds(1));
mosquitto_disconnect(mosq_);
mosquitto_destroy(mosq_);
mosquitto_lib_cleanup();
return 0;
}
```